<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="计划名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入计划名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"> 搜索 </el-button>
              <el-button icon="Refresh" @click="resetQuery"> 重置 </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="计划名称" align="center" show-overflow-tooltip prop="name" width="150" />
        <el-table-column label="计划编号" align="center" show-overflow-tooltip prop="id" width="150" />
        <el-table-column label="巡检类型" align="center">
          <template #default="scope">
            <dict-tag :options="inspection_type" :value="scope.row.inspectionType" />
          </template>
        </el-table-column>
        <el-table-column label="巡检范围" align="center" width="120">
          <template #default="scope">
            <dict-tag :options="inspection_range" :value="scope.row.inspectionType" />
          </template>
        </el-table-column>
        <el-table-column label="巡检周期（天）" align="center" show-overflow-tooltip prop="inspectionCycle" width="150" />
        <el-table-column label="已巡检/待巡检项" align="center" show-overflow-tooltip prop="inspectionCycle" width="150">
          <template #default="{ row }">
            {{ row.itemsDone }} / {{ row.itemsTotal }}
          </template>
        </el-table-column>
        <el-table-column label="完成度" align="center" show-overflow-tooltip prop="completeRate" width="150" />
        <el-table-column label="巡检员" align="center" show-overflow-tooltip prop="ext1.inspectionPersonName" />
        <el-table-column label="操作" align="center" width="140" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button size="small" link type="primary" @click="handleCheck(scope.row)">执行巡检</el-button>
            <el-button size="small" link type="primary" @click="handleRepair(scope.row)">故障报修</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1100px" append-to-body>
      <el-form ref="addFormRef" :model="form" label-width="110px">
        <div class="drawer-title">
          <el-descriptions title="" direction="vertical" :column="5">
            <el-descriptions-item align="center" label="计划名称">{{ form.name }}</el-descriptions-item>
            <el-descriptions-item align="center" label="计划编号">{{ form.id }}</el-descriptions-item>
            <el-descriptions-item align="center" label="巡检类型">
              <dict-tag :options="inspection_type" :value="form.inspectionType" />
            </el-descriptions-item>
            <el-descriptions-item align="center" label="巡检周期(天)">{{ form.inspectionCycle }}</el-descriptions-item>
            <el-descriptions-item align="center" label="巡检员">{{ form.ext1.inspectionPersonName }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <SubTitle title="基础信息" style="margin-top: 10px;" />
        <el-table :data="form.inspectionItem" max-height="300">
          <el-table-column label="设备名称" align="center" show-overflow-tooltip width="120" prop="device_name">
          </el-table-column>
          <el-table-column label="设备编号" align="center" width="120" prop="device_sn">
          </el-table-column>
          <el-table-column label="巡检项目名称" align="center" width="150" prop="name">
          </el-table-column>
          <el-table-column label="检验方法" align="center" show-overflow-tooltip prop="detection_method">
          </el-table-column>
          <el-table-column label="检验标准" align="center" show-overflow-tooltip prop="detection_standard">
          </el-table-column>
          <el-table-column label="判断标准" align="center" show-overflow-tooltip prop="judge_standard">
          </el-table-column>
          <el-table-column label="标准上限" align="center" prop="judge_max_value">
            <template #default="{ row }">
              {{ row.judge_max_value || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="标准下限" align="center" prop="judge_min_value">
            <template #default="{ row }">
              {{ row.judge_min_value || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="巡检结果" width="100" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.inspectionResult" placeholder="请输入" />
            </template>
          </el-table-column>
          <el-table-column label="巡检备注说明" width="120" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.inspectionRemark" placeholder="请输入" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"> 确 定 </el-button>
          <el-button @click="cancel"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="repairDialog.visible" :title="repairDialog.title" width="800px" append-to-body>
      <el-form ref="repairFormRef" :model="repairForm" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报修主题" prop="name" :rules="[{ required: true, message: '报修主题不能为空', trigger: 'blur' }]">
              <el-input v-model="repairForm.name" placeholder="请输入报修主题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障设备" prop="deviceId"
              :rules="[{ required: true, message: '故障设备不能为空', trigger: 'change' }]">
              <el-select v-model="repairForm.deviceId" clearable placeholder="请选择故障设备">
                <el-option v-for="item in deviceOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障等级" prop="faultLevel"
              :rules="[{ required: true, message: '故障等级不能为空', trigger: 'change' }]">
              <el-select v-model="repairForm.faultLevel" clearable placeholder="请选择故障等级">
                <el-option v-for="item in fault_level" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障类型" prop="faultTypeId"
              :rules="[{ required: true, message: '故障类型不能为空', trigger: 'blur' }]">
              <el-select v-model="repairForm.faultTypeId" clearable placeholder="请选择故障故障类型">
                <el-option v-for="item in faultTypeOptions" :key="item.id" :label="item.name"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障发生时间" prop="faultTime"
              :rules="[{ required: true, message: '故障发生时间不能为空', trigger: 'change' }]">
              <el-date-picker v-model="repairForm.faultTime" style="width: 100%;" value-format="YYYY-MM-DD hh:mm:ss"
                type="datetime" placeholder="选择时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否停机" prop="isstop">
              <el-switch v-model="repairForm.isstop" active-value="1" inactive-value="0" active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障描述" prop="remark">
              <el-input v-model="repairForm.remark" type="textarea" placeholder="请输入故障描述" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="repairFormSubmit"> 确 定 </el-button>
          <el-button @click="repairCancel"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PatrolTask" lang="ts">
import { listInspectionTask, addInspectionTaskRecord, getInspectionTaskInfoById, updateInspectionTaskRecord } from '@/api/deviceCheck/index';
import { listFaultType,addFault } from '@/api/deviceMaintain/index';
import { listDevice } from '@/api/deviceManage/device'
import { deepClone, dateFormat } from '@/utils';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const tableList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const addFormRef = ref<ElFormInstance>();
const repairFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const repairDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const repairForm = ref({
  id: undefined,
  name: undefined,
  deviceId: undefined,
  faultLevel: undefined,
  faultTypeId: undefined,
  isstop: undefined,
  faultTime: undefined,
  remark: undefined,
} as any)
const initFormData = {
  id: undefined,
  recordId: undefined,
  name: undefined,
  startTime: undefined,
  endTime: undefined,
  inspectionType: undefined,
  inspectionCycle: 1,
  status: 0,
  inspectionRange: undefined,
  inspectionPersonId: undefined,
  inspectionItem: [],
  remark: undefined,
  ext1: <any>{
  },
  ext2: undefined
};
const formData = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    status: '1',
    params: {}
  }
});
const { queryParams, form } = toRefs(formData);
const { inspection_type } = toRefs<any>(proxy?.useDict('inspection_type'));
const { inspection_range } = toRefs<any>(proxy?.useDict('inspection_range'));
const { fault_level } = toRefs<any>(proxy?.useDict('fault_level'));
const deviceOptions = ref([])
const faultTypeOptions = ref([])
/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listInspectionTask(queryParams.value);
  tableList.value = res.rows.map((item) => ({
    ...item,
    ext1: item.ext1 ? JSON.parse(item.ext1) : null,
  }));
  tableList.value.forEach(async item => {
    const { data } = await getInspectionTaskInfoById(item.id)
    Object.assign(item, data, { itemsTotal: data.inspectionItem.length, itemsDone: data.inspectionItem.filter(item => item.inspectionResult.trim() !== '').length })
    item.completeRate = (item.itemsDone / item.itemsTotal * 100).toFixed(2) + '%'
  })

  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};
const repairCancel = () => {
  repairFormRef.value?.resetFields();
  repairDialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...deepClone(initFormData) };
  addFormRef.value?.resetFields();
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
const handleCheck = async (row) => {
  reset();
  Object.assign(form.value, row);
  dialog.visible = true;
  dialog.title = '执行巡检任务';
}
/** 修改按钮操作 */
const handleRepair = () => {
  repairFormRef.value?.resetFields();
  repairDialog.visible = true;
  repairDialog.title = '巡检故障报修';
};

/** 提交按钮 */
const submitForm = () => {
  addFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const { inspectionItem, id, recordId } = form.value
      if (inspectionItem.every(item => item.inspectionResult.trim() === '')) return proxy.$modal.msgError('请填写巡检结果')
      buttonLoading.value = true;
      if (!recordId) {
        await addInspectionTaskRecord({
          taskId: id,
          inspectionStatus: '0',
          inspectionItem,
        })
      } else {
        const params = {
          id: recordId,
          inspectionItem
        } as any
        if (inspectionItem.every(item => item.inspectionResult.trim() !== '')) {
          params.inspectionStatus = '1'
          params.inspectionEndDate = dateFormat(new Date(), 'yyyy-MM-dd')
        }
        await updateInspectionTaskRecord(params)
      }
      buttonLoading.value = false;
      dialog.visible = false;
      proxy.$modal.msgSuccess('提交成功');
      getList();
    }
  });
};
const repairFormSubmit = () => {
  repairFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await addFault(repairForm.value).finally(() => (buttonLoading.value = false));
      repairDialog.visible = false;
      proxy.$modal.msgSuccess('提交成功');
    }
  });
};
const getDeviceList = () => {
  listDevice({}).then(({ code, rows }) => {
    if (code === 200) {
      deviceOptions.value = rows
    }
  })
}
const getFaultTypeList = () => {
  listFaultType({}).then(({ code, rows }) => {
    if (code === 200) {
      faultTypeOptions.value = rows
    }
  })
}
onMounted(() => {
  getList();
  getDeviceList();
  getFaultTypeList();
});
</script>
<style lang="scss" scoped>
.operateBtn {
  display: flex;
  align-items: center;

  .el-icon {
    color: #409eff;
    margin-left: 5px;
    cursor: pointer;
  }
}

.drawer-title {
  :deep(.el-descriptions__body) {
    margin-top: 10px;
    background-color: #F4F5F7;
    border-radius: 2px;
    padding: 10px 10px 0 10px;
  }

  :deep(.el-descriptions__label) {
    padding-bottom: 5px;
  }

  .title-name {
    color: #000;
  }
}
</style>
