<template>

  <el-row :gutter="20">
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="设备类别" prop="deviceType">
            <el-tree-select
              v-model="formData.deviceType"
              :data="productClassifyList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择设备类别"
              @change="assetclasschange"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="设备部件" prop="deviceComponent">
            <el-input
              v-model="queryParams.deviceComponent"
              placeholder="请输入设备部件"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="创建人" prop="creName">
            <el-input
              v-model="queryParams.creName"
              placeholder="请输入创建人"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="创建日期" prop="creDate">
            <el-date-picker
              v-model="queryParams.creDate"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="date"
              start-placeholder="请选择"
              :default-time="[new Date('1 00:00:00')]"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['rq:iot-operation-model:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['rq:iot-operation-model:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="所属组织" align="center" prop="orgName" />
          <el-table-column label="设备类别" align="center" prop="deviceType" />
          <el-table-column label="设备部件" align="center" prop="deviceComponent" />
          <el-table-column label="填写信息" align="center" prop="fillInfo" />
          <el-table-column label="创建人" align="center" prop="creName" />
          <el-table-column
            label="创建日期"
            align="center"
            prop="creDate"
            :formatter="dateFormatter2"
            width="180px"
          />
          <el-table-column label="操作" align="center" min-width="120px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['rq:iot-operation-model:update']"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['rq:iot-operation-model:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>


    <!-- 表单弹窗：添加/修改 -->
    <IotOpeationModelForm ref="formRef" @success="getList" :dept="deptInfo"/>
  </el-row>
</template>

<script setup lang="ts">
import { dateFormatter2 } from '@/utils/formatTime'
import DeptTree from "@/views/system/user/DeptTree.vue";
import download from '@/utils/download'
import {defaultProps,handleTree} from "@/utils/tree";
import { IotOpeationModelApi, IotOpeationModelVO } from '@/api/pms/iotopeationmodel'
import IotOpeationModelForm from './IotOpeationModelForm.vue'
import * as DeptApi from "@/api/system/dept";
import * as ProductClassifyApi from "@/api/pms/productclassify";
import {IotDeviceApi} from "@/api/pms/device";
import {DeviceAttrModelApi} from "@/api/pms/deviceattrmodel";

/** 运行记录模板主 列表 */
defineOptions({ name: 'IotOpeationModel' })

const message = useMessage() // 消息弹窗

const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<IotOpeationModelVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const { push } = useRouter() // 路由跳转
const deptList = ref<Tree[]>([]) // 树形结构
const productClassifyList = ref<Tree[]>([]) // 树形结构
const { params, name } = useRoute() // 查询参数
const id = params.id
const brandLabel = ref('') // 表单的类型：create - 新增；update - 修改
const zzLabel = ref('') // 表单的类型：create - 新增；update - 修改
const supplierLabel = ref('') // 表单的类型：create - 新增；update - 修改

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptId: undefined,
  orgName: undefined,
  deviceType: undefined,
  deviceComponent: undefined,
  fillInfo: undefined,
  creName: undefined,
  creDate: [],
})
let deptInfo = {deptId:'',orgName:''};
const formData = ref({
  deviceType: undefined
})
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await IotOpeationModelApi.getIotOpeationModelPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  //修改

  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await IotOpeationModelApi.deleteIotOpeationModel(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await IotOpeationModelApi.exportIotOpeationModel(queryParams)
    download.excel(data, '运行记录模板主.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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

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 handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  queryParams.orgName = row.name;
  deptInfo.orgName = queryParams.orgName;
  deptInfo.deptId = queryParams.deptId;
  await getList()
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
