<template>
  <ContentWrap v-loading="formLoading">
    <el-form ref="formRef" :model="formData" :rules="formRules" style="margin-right: 4em;margin-left: 0.5em" label-width="130px">
      <div class="title-div">
        <el-button @click="baseInfoClick" class="title-button">
          <Icon color="black" icon="ep:set-up" :size="18" class="cursor-pointer first-icon" />
          <span class="cursor-pointer">基本信息</span>
          <Icon
            color="black"
            :icon="baseIsExpanded ? 'fa-solid:angle-double-down' : 'fa-solid:angle-double-right'"
            :size="18"
            class="cursor-pointer"
          />
        </el-button>
      </div>
      <div class="base-expandable-content" :class="{ 'is-expanded': baseIsExpanded }">
        <el-row>
          <el-col :span="6">
            <el-form-item label="资产编码" prop="deviceCode">
              <el-input v-model="formData.deviceCode" placeholder="请输入资产编码" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="formData.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品牌" prop="brand">
              <el-select
                v-model="formData.brand"
                :model-value="brandLabel"
                placeholder="请输入品牌"
                @click="openForm"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所在部门" prop="deptId">
              <el-tree-select
                v-model="formData.deptId"
                :data="deptList"
                :props="defaultProps"
                check-strictly
                node-key="id"
                placeholder="请选择所在部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="资产类别" prop="assetClass">
              <el-tree-select
                v-model="formData.assetClass"
                :data="productClassifyList"
                :props="defaultProps"
                check-strictly
                node-key="id"
                placeholder="请选择资产类别"
                @change="assetclasschange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备状态" prop="deviceStatus">
              <el-select v-model="formData.deviceStatus" placeholder="请选择">
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.PMS_DEVICE_STATUS)"
                  :key="dict.label"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="资产性质" prop="deviceStatus">
              <el-select v-model="formData.assetProperty" placeholder="请选择">
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.PMS_ASSET_PROPERTY)"
                  :key="dict.id"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格型号" prop="model">
              <el-select
                v-model="formData.model"
                :model-value="modelLabel"
                placeholder="请输入规格型号"
                @click="openModelForm"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="图片" prop="picUrl">
              <UploadImg v-model="formData.picUrl" :disabled="isDetail" height="60px" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="title-div">
        <el-button @click="zzInfoClick" class="title-button">
          <Icon color="black" icon="ep:set-up" :size="18" class="cursor-pointer first-icon" />
          <span class="cursor-pointer">制造信息</span>
          <Icon
            color="black"
            :icon="zzIsExpanded ? 'fa-solid:angle-double-down' : 'fa-solid:angle-double-right'"
            :size="18"
            class="cursor-pointer"
          />
        </el-button>
      </div>
      <div class="zz-expandable-content" :class="{ 'is-expanded': zzIsExpanded }">
        <el-row>
          <el-col :span="6">
            <el-form-item label="制造商" prop="manufacturerId">
              <el-select
                v-model="formData.manufacturerId"
                :model-value="zzLabel"
                placeholder="请输入制造商"
                @click="openCustomer('manufacturer')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产日期" prop="manDate">
              <el-date-picker
                style="width: 150%"
                v-model="formData.manDate"
                type="date"
                value-format="x"
                placeholder="选择生产日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商" prop="supplierId">
              <el-select
                v-model="formData.supplierId"
                placeholder="请输入供应商"
                :model-value="supplierLabel"
                @click="openCustomer('supplier')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质保到期" prop="expires">
              <el-date-picker
                style="width: 150%"
                v-model="formData.expires"
                type="date"
                value-format="x"
                placeholder="选择质保到期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="铭牌信息" prop="nameplate">
              <el-input v-model="formData.nameplate" type="textarea" placeholder="请输入铭牌信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="title-div">
        <el-button @click="cwInfoClick" class="title-button">
          <Icon color="black" icon="ep:set-up" :size="18" class="cursor-pointer first-icon" />
          <span class="cursor-pointer">财务信息</span>
          <Icon
            color="black"
            :icon="cwIsExpanded ? 'fa-solid:angle-double-down' : 'fa-solid:angle-double-right'"
            :size="18"
            class="cursor-pointer"
          />
        </el-button>
      </div>
      <div class="cw-expandable-content" :class="{ 'is-expanded': cwIsExpanded }">
        <el-row>
          <el-col :span="6">
            <el-form-item :label="formData.assetProperty==='zy'?'采购价格':'租赁价格'" prop="plPrice">
              <el-input
                v-model="formData.plPrice"
                @input="handleInput(formData.plPrice, 'plPrice')"
                :placeholder="formData.assetProperty==='zy'?'请输入采购价格':'请输入租赁价格'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="formData.assetProperty==='zy'?'采购日期':'租赁日期'" prop="plDate">
              <el-date-picker
                style="width: 150%"
                v-model="formData.plDate"
                type="date"
                value-format="x"
                :placeholder="formData.assetProperty==='zy'?'请输入采购日期':'请输入租赁日期'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="formData.assetProperty==='zy'?'折旧年限':'租赁年限'" prop="plYear">
              <el-input v-model="formData.plYear" type="number" :placeholder="formData.assetProperty==='zy'?'请输入折旧年限':'请输入租赁年限'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="formData.assetProperty==='zy'?'折旧开始日期':'租赁开始日期'" prop="plStartDate">
              <el-date-picker
                style="width: 150%"
                v-model="formData.plStartDate"
                type="date"
                value-format="x"
                :placeholder="formData.assetProperty==='zy'?'请选择折旧开始日期':'请选择租赁开始日期'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="formData.assetProperty==='zy'?'已提折旧月数':'已租赁月数'" prop="plMonthed">
              <el-input
                v-model="formData.plMonthed"
                type="number"
                :placeholder="formData.assetProperty==='zy'?'请输入已提折旧月数':'请输入已租赁月数'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="formData.assetProperty==='zy'?'已提折旧金额':'已租赁金额'" prop="plAmounted">
              <el-input
                v-model="formData.plAmounted"
                @input="handleInput(formData.plAmounted, 'plAmounted')"
                :placeholder="formData.assetProperty==='zy'?'请输入已提折旧金额':'已租赁金额'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="剩余金额" prop="remainAmount">
              <el-input
                v-model="formData.remainAmount"
                @input="handleInput(formData.remainAmount, 'remainAmount')"
                placeholder="请输入剩余金额"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="title-div">
        <el-button @click="qtInfoClick" class="title-button">
          <Icon color="black" icon="ep:set-up" :size="18" class="cursor-pointer first-icon" />
          <span class="cursor-pointer">其它信息</span>
          <Icon
            color="black"
            :icon="qtIsExpanded ? 'fa-solid:angle-double-down' : 'fa-solid:angle-double-right'"
            :size="18"
            class="cursor-pointer"
          />
        </el-button>
      </div>
      <div class="qt-expandable-content" :class="{ 'is-expanded': qtIsExpanded }">
        <el-row>
          <el-col v-for="field in list" :key="field.sort" :span="6">
            <el-form-item :label="field.name" :prop="field.identifier" :rules="field.rules">
              <!-- 文本输入 -->
              <el-input
                v-if="field.type === 'text'"
                v-model="formData[field.identifier]"
                :placeholder="'请输入' + field.name"
                :type="field.type || 'text'"
                clearable
                :model-value="field.value"
              />

              <el-select
                v-else-if="field.type === 'select'"
                v-model="formData[field.identifier]"
                :placeholder="'请输入'+field.name"
                clearable
                filterable
              >
                <el-option
                  v-for="item in field.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <!-- 数字输入 -->
              <el-input
                v-else-if="field.type === 'int'"
                type="number"
                v-model="formData[field.identifier]"
                style="width: 150%"
              />
              <el-input
                v-else-if="field.type === 'double'"
                v-model="formData[field.identifier]"
                @input="handleInput(formData[field.identifier], field.identifier)"
                style="width: 150%"
              />
              <!-- 日期选择 -->
              <el-date-picker
                v-else-if="field.type === 'date'"
                v-model="formData[field.identifier]"
                :type="field.type || 'date'"
                :placeholder="'请输入' + field.name"
                value-format="YYYY-MM-DD"
                style="width: 150%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <el-form>
      <el-form-item style="float: right">
        <el-button type="success" @click="allzhankai">一键展开</el-button>
        <el-button type="info" @click="allshouqi">一键收起</el-button>
        <el-button v-if="!isDetail" :loading="formLoading" type="warning" @click="submitForm">
          保存
        </el-button>
        <el-button @click="close" type="primary">返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <BrandList ref="brandFormRef" @choose="brandChoose" />
  <ModelList ref="modelFormRef" @choose="modelChoose" />
  <CustomerList ref="customerFormRef" @choose="customerChoose" />
</template>
<script setup lang="ts">
import { IotDeviceApi, IotDeviceVO } from '@/api/pms/device'
import BrandList from '@/views/pms/device/BrandList.vue'
import ModelList from '@/views/pms/device/ModelList.vue'
import CustomerList from '@/views/pms/device/CustomerList.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as ProductClassifyApi from '@/api/pms/productclassify'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { useTagsViewStore } from '@/store/modules/tagsView'
import {DeviceAttrModelApi} from "@/api/pms/deviceattrmodel";


/** 设备台账 表单 */
defineOptions({ name: 'IotDeviceForm' })
const baseIsExpanded = ref(true) // 控制表单是否展开的变量
const zzIsExpanded = ref(true) // 控制表单是否展开的变量
const cwIsExpanded = ref(true) // 控制表单是否展开的变量
const qtIsExpanded = ref(true) // 控制表单是否展开的变量

const deptList = ref<Tree[]>([]) // 树形结构
const productClassifyList = ref<Tree[]>([]) // 树形结构
const { delView } = useTagsViewStore() // 视图操作
const { params, name } = useRoute() // 查询参数
const { currentRoute, push } = useRouter()
const id = params.id
const isDetail = params.isDetail
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const brandLabel = ref('') // 表单的类型：create - 新增；update - 修改
const modelLabel = ref('') // 表单的类型：create - 新增；update - 修改
const zzLabel = ref('') // 表单的类型：create - 新增；update - 修改
const supplierLabel = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  brand: undefined,
  model: undefined,
  deptId: undefined,
  deviceStatus: undefined,
  assetProperty: undefined,
  picUrl: undefined,
  remark: undefined,
  manufacturerId: undefined,
  supplierId: undefined,
  manDate: undefined,
  nameplate: undefined,
  expires: undefined,
  plPrice: undefined,
  plDate: undefined,
  plYear: undefined,
  plStartDate: undefined,
  plMonthed: undefined,
  plAmounted: undefined,
  remainAmount: undefined,
  infoId: undefined,
  infoType: undefined,
  infoName: undefined,
  infoRemark: undefined,
  infoUrl: undefined,
  templateJson: undefined,
  assetClass: undefined
})
const formRules = reactive({
  assetClass: [{ required: true, message: '资产类别不能为空', trigger: 'blur' }],
  deviceCode: [{ required: true, message: '资产编码不能为空', trigger: 'blur' }],
  deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  brand: [{ required: true, message: '品牌不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '所在部门不能为空', trigger: 'blur' }],
  deviceStatus: [{ required: true, message: '设备状态不能为空', trigger: 'blur' }],
  assetProperty: [{ required: true, message: '资产性质不能为空', trigger: 'blur' }],
  manufacturerId: [{ required: true, message: '制造商id不能为空', trigger: 'blur' }],
  manDate: [{ required: true, message: '生产日期不能为空', trigger: 'blur' }]
})

const list = ref([])

const assetclasschange = () => {
  const assetClass = formData.value.assetClass
  DeviceAttrModelApi.getDeviceAttrModelListByDeviceCategoryId(assetClass).then(res => {
    if (res){
      debugger
      res.forEach((item) => {
        if (item.requiredFlag) {
          const rule = {required: true, message: item.name+'不能为空', trigger: 'blur'}
          item.rules = []
          item.rules.push(rule)
        }
      })
      list.value = res
    } else {
      list.value = []
    }
  })
}

const brandChoose = (row) => {
  formData.value.brand = row.id
  brandLabel.value = row.value
}
const modelChoose = (row) => {
  formData.value.model = row.name
  modelLabel.value = row.value
}
const customerChoose = (row) => {
  formData.value[row.customerNature + 'Id'] = row.id
  if (row.customerNature == 'supplier') {
    supplierLabel.value = row.name
  } else {
    zzLabel.value = row.name
  }
}
/** 添加/修改操作 */
const brandFormRef = ref()
const openForm = () => {
  brandFormRef.value.open()
}
const modelFormRef = ref()
const openModelForm = () =>{
  modelFormRef.value.open()
}
const customerFormRef = ref()
const openCustomer = (type) => {
  customerFormRef.value.open(type)
}
const allshouqi = () => {
  baseIsExpanded.value = false
  zzIsExpanded.value = false
  cwIsExpanded.value = false
  qtIsExpanded.value = false
}
const allzhankai = () => {
  baseIsExpanded.value = true
  zzIsExpanded.value = true
  cwIsExpanded.value = true
  qtIsExpanded.value = true
}

const handleInput = (value, obj) => {
  // 1. 过滤非法字符（只允许数字和小数点）
  let filtered = value.replace(/[^\d.]/g, '')

  // 2. 处理多个小数点的情况
  filtered = filtered.replace(/\.{2,}/g, '.')

  // 3. 限制小数点后最多两位
  let decimalParts = filtered.split('.')
  if (decimalParts.length > 1) {
    decimalParts = decimalParts.slice(0, 2)
    filtered = decimalParts.join('.')
  }

  // 4. 处理以小数点开头的情况（自动补0）
  if (filtered.startsWith('.')) {
    filtered = '0' + filtered
  }

  // 5. 更新绑定值（同时处理连续输入多个0的情况）
  formData.value[obj] = filtered.replace(/^0+(?=\d)/, '')
}

const close = () => {
  delView(unref(currentRoute))
  push({
    name: 'IotDevicePms',
    query: {
      date: new Date().getTime()
    }
  })
}
const baseInfoClick = () => {
  baseIsExpanded.value = !baseIsExpanded.value // 切换展开状态
}
const zzInfoClick = () => {
  zzIsExpanded.value = !zzIsExpanded.value // 切换展开状态
}
const cwInfoClick = () => {
  cwIsExpanded.value = !cwIsExpanded.value // 切换展开状态
}
const qtInfoClick = () => {
  qtIsExpanded.value = !qtIsExpanded.value // 切换展开状态
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const formRef = ref()
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    if (list.value) {
      list.value.forEach((item) => {
        item.value = formData.value[item.identifier]
      })
    }
    formData.value.templateJson = JSON.stringify(list.value)
    const data = formData.value as unknown as IotDeviceVO
    if (formType.value === 'create') {
      await IotDeviceApi.createIotDevice(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotDeviceApi.updateIotDevice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    //emit('success')
    delView(unref(currentRoute))
    await push({
      name: 'IotDevicePms', query: {
        date: new Date().getTime(),
      }
    })
  } finally {
    formLoading.value = false
  }
}

onMounted(async () => {
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  productClassifyList.value = handleTree(
    await ProductClassifyApi.IotProductClassifyApi.getSimpleProductClassifyList()
  )
  formData.value.assetProperty = 'zy'
  // 修改时，设置数据
  if (id) {
    formType.value = 'update';
    formLoading.value = true
    try {
      const iotDevice = await IotDeviceApi.getIotDevice(id);
      formData.value = iotDevice
      brandLabel.value = iotDevice.brandName;
      zzLabel.value = iotDevice.zzName;
      supplierLabel.value = iotDevice.supplierName;
      list.value = JSON.parse(iotDevice.templateJson);
      list.value.forEach((item) => {
        formData.value[item.identifier] = item.value;
      })
    } finally {
      formLoading.value = false
    }
  } else {
    formType.value = 'create';
  }
})
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceCode: undefined,
    deviceName: undefined,
    brand: undefined,
    model: undefined,
    deptId: undefined,
    deviceStatus: undefined,
    assetProperty: undefined,
    picUrl: undefined,
    remark: undefined,
    manufacturerId: undefined,
    supplierId: undefined,
    manDate: undefined,
    nameplate: undefined,
    expires: undefined,
    plPrice: undefined,
    plDate: undefined,
    plYear: undefined,
    plStartDate: undefined,
    plMonthed: undefined,
    plAmounted: undefined,
    remainAmount: undefined,
    infoId: undefined,
    infoType: undefined,
    infoName: undefined,
    infoRemark: undefined,
    infoUrl: undefined,
    templateJson: undefined,
    assetClass: undefined,

  }
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss">
.base-expandable-content {
  max-height: 0; /* 初始高度为0 */
  overflow: hidden; /* 隐藏溢出的内容 */
  transition: max-height 0.3s ease; /* 平滑过渡效果 */
}

.base-expandable-content.is-expanded {
  max-height: 200px; /* 或者根据内容设定一个合适的最大高度 */
}
.zz-expandable-content {
  max-height: 0; /* 初始高度为0 */
  overflow: hidden; /* 隐藏溢出的内容 */
  transition: max-height 0.3s ease; /* 平滑过渡效果 */
}

.zz-expandable-content.is-expanded {
  max-height: 200px; /* 或者根据内容设定一个合适的最大高度 */
}
.cw-expandable-content {
  max-height: 0; /* 初始高度为0 */
  overflow: hidden; /* 隐藏溢出的内容 */
  transition: max-height 0.3s ease; /* 平滑过渡效果 */
}

.cw-expandable-content.is-expanded {
  max-height: 200px; /* 或者根据内容设定一个合适的最大高度 */
}
.qt-expandable-content {
  max-height: 0; /* 初始高度为0 */
  overflow: hidden; /* 隐藏溢出的内容 */
  transition: max-height 0.3s ease; /* 平滑过渡效果 */
}

.qt-expandable-content.is-expanded {
  max-height: 200px; /* 或者根据内容设定一个合适的最大高度 */
}
.title-button{
  font-size: 18px;
  border: none;
}
.title-div{
  margin-bottom: 20px;
  margin-top: 10px;
}
.cursor-pointer{
  vertical-align: middle;
}
.first-icon{
  margin-bottom: 2px;
}
</style>
