<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">
        <BreadcrumbBack />
        编辑危险源清单
      </div>
    </header>
    <main class="safety-platform-container__main">
      <el-form ref="formRef" :inline="true" label-width="auto" :model="formValue" :rules="rules">
        <!-- 基础信息 -->
        <el-divider content-position="left">基础信息</el-divider>
        <el-form-item label="危险源编号" prop="hazardCode">
          <el-input
            v-model="formValue.hazardCode"
            size="large"
            placeholder="例如：RD-202311-042"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item label="关键过程/作业单元" prop="keyProcessUnit">
          <el-input
            v-model="formValue.keyProcessUnit"
            size="large"
            placeholder="例如：张江快堆实验室(10号楼)"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item label="危险源名称" prop="hazardName">
          <el-input
            v-model="formValue.hazardName"
            size="large"
            placeholder="例如：高温熔融金属操作"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item label="是否重大危险源" prop="isMajorHazard">
          <el-select v-model="formValue.isMajorHazard" size="large" placeholder="请选择" style="width: 330px">
            <el-option :value="1" label="是" />
            <el-option :value="0" label="否" />
          </el-select>
        </el-form-item>
        <el-form-item label="危险源来源" prop="hazardSource">
          <el-input
            v-model="formValue.hazardSource"
            size="large"
            placeholder="例如：作业单元划分"
            style="width: 330px"
          />
        </el-form-item>

        <!-- 部门责任 -->
        <el-form-item label="涉及部门" prop="involvedDepartment">
          <el-input
            v-model="formValue.involvedDepartment"
            size="large"
            placeholder="例如：核材料研究部/设备管理部（支持手动输入多部门）"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item label="风险管理部门" prop="riskManagementDept">
          <!-- <el-cascader
            :ref="(el) => (cascaderRef['riskManagementDept'] = el)"
            v-model="formValue.riskManagementDeptId"
            size="large"
            style="width: 330px"
            :options="firstLevelDepts"
            :props="cascaderProp"
            :show-all-levels="false"
            placeholder="请选择"
            filterable
            @change="() => handleChangeDept('riskManagementDept')"
          /> -->
          <el-input size="large" placeholder="请选择" v-model="formValue.riskManagementDept" style="width: 330px" />
        </el-form-item>
        <el-form-item label="协作部门" prop="cooperationDept">
          <!-- <el-cascader
            v-model="formValue.cooperationDeptId"
            :ref="(el) => (cascaderRef['cooperationDept'] = el)"
            size="large"
            style="width: 330px"
            :options="firstLevelDepts"
            :props="cascaderProp"
            :show-all-levels="false"
            placeholder="请选择"
            filterable
            @change="handleChangeDept('cooperationDept')"
          /> -->
          <el-input size="large" placeholder="请选择" v-model="formValue.cooperationDept" style="width: 330px" />
        </el-form-item>

        <!-- 风险评估 -->
        <el-form-item label="可能后果" prop="possibleConsequences">
          <el-input
            v-model="formValue.possibleConsequences"
            size="large"
            placeholder="例如：灼伤、火灾"
            style="width: 330px"
          />
        </el-form-item>

        <el-divider content-position="left">固有风险评估</el-divider>
        <el-form-item label="可能性(M)" prop="inherentRiskM">
          <!-- <el-select v-model="formValue.inherentRiskM" size="large" placeholder="1-5" style="width: 330px">
            <el-option v-for="n in 5" :key="n" :label="n" :value="n" />
          </el-select> -->
          <el-input-number :step="1" :precision="0" v-model="formValue.inherentRiskM" :min="1" style="width: 330px" />
        </el-form-item>
        <el-form-item label="暴露频率(E)" prop="inherentRiskE">
          <!-- <el-select v-model="formValue.inherentRiskE" size="large" placeholder="1-6" style="width: 330px">
            <el-option v-for="n in 6" :key="n" :label="n" :value="n" />
          </el-select> -->
          <el-input-number :step="1" :precision="0" v-model="formValue.inherentRiskE" :min="1" style="width: 330px" />
        </el-form-item>
        <el-form-item label="严重度(S)" prop="inherentRiskS">
          <!-- <el-select v-model="formValue.inherentRiskS" size="large" placeholder="1-5" style="width: 330px">
                  <el-option v-for="n in 5" :key="n" :label="n" :value="n" />
                </el-select> -->
          <el-input-number :step="1" :precision="0" v-model="formValue.inherentRiskS" :min="1" style="width: 330px" />
        </el-form-item>
        <el-form-item label="风险值(R)" prop="inherentRiskR">
          <el-input
            v-model="formValue.inherentRiskR"
            size="large"
            disabled
            placeholder="自动计算: M×E×S"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item label="风险等级" prop="inherentRiskLevel">
          <el-select v-model="formValue.inherentRiskLevel" size="large" placeholder="请选择" style="width: 330px">
            <!-- <el-option label="A" value="A" /> -->
            <el-option label="B" value="B" />
            <el-option label="C" value="C" />
            <!-- <el-option label="D" value="D" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="升级等级" prop="inherentRiskUpgrade">
          <el-input v-model="formValue.inherentRiskUpgrade" size="large" placeholder="例如：2级" style="width: 330px" />
        </el-form-item>

        <!-- 管控措施 -->
        <el-divider content-position="left">管控措施</el-divider>
        <el-form-item label="主要管控措施" prop="controlMeasures">
          <el-input
            type="textarea"
            :rows="3"
            v-model="formValue.controlMeasures"
            size="large"
            placeholder="每条措施用分号分隔，例如：1.穿戴防护服;2.设置隔离区;3.定期检查冷却系统"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item label="主责部门" prop="controlMainDept">
          <!-- <el-cascader
            v-model="formValue.controlMainDeptId"
            :ref="(el) => (cascaderRef['controlMainDept'] = el)"
            size="large"
            style="width: 330px"
            :options="firstLevelDepts"
            :props="cascaderProp"
            :show-all-levels="false"
            placeholder="请选择"
            filterable
            @change="handleChangeDept('controlMainDept')"
          /> -->
          <el-input size="large" placeholder="请选择" v-model="formValue.controlMainDept" style="width: 330px" />
        </el-form-item>
        <el-form-item label="协作部门" prop="controlCoopDept">
          <!-- <el-cascader
            v-model="formValue.controlCoopDeptId"
            :ref="(el) => (cascaderRef['controlCoopDept'] = el)"
            size="large"
            style="width: 330px"
            :options="firstLevelDepts"
            :props="cascaderProp"
            :show-all-levels="false"
            placeholder="请选择"
            filterable
            @change="handleChangeDept('controlCoopDept')"
          /> -->
          <el-input size="large" placeholder="请选择" v-model="formValue.controlCoopDept" style="width: 330px" />
        </el-form-item>
        <el-form-item label="完成期限" prop="completionDeadline">
          <el-date-picker
            v-model="formValue.completionDeadline"
            type="date"
            size="large"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item label="完成状态" prop="completionStatus">
          <el-input
            v-model="formValue.completionStatus"
            size="large"
            placeholder="例如：措施1,2已完成"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item label="验证状态" prop="verificationStatus">
          <el-input
            v-model="formValue.verificationStatus"
            size="large"
            placeholder="例如：措施1已验证"
            style="width: 330px"
          />
        </el-form-item>

        <!-- 剩余风险 -->
        <el-divider content-position="left">剩余风险评估</el-divider>
        <el-form-item label="可能性(M)" prop="controlRiskM">
          <!-- <el-select v-model="formValue.controlRiskM" size="large" placeholder="1-5" style="width: 330px">
            <el-option v-for="n in 5" :key="n" :label="n" :value="n" />
          </el-select> -->
          <el-input-number :step="1" :precision="0" v-model="formValue.controlRiskM" :min="1" style="width: 330px" />
        </el-form-item>
        <el-form-item label="暴露频率(E)" prop="controlRiskE">
          <!-- <el-select v-model="formValue.controlRiskE" size="large" placeholder="1-6" style="width: 330px">
            <el-option v-for="n in 6" :key="n" :label="n" :value="n" />
          </el-select> -->
          <el-input-number :step="1" :precision="0" v-model="formValue.controlRiskE" :min="1" style="width: 330px" />
        </el-form-item>
        <el-form-item label="严重度(S)" prop="controlRiskS">
          <!-- <el-select v-model="formValue.controlRiskS" size="large" placeholder="1-5" style="width: 330px">
            <el-option v-for="n in 5" :key="n" :label="n" :value="n" />
          </el-select> -->
          <el-input-number :step="1" :precision="0" v-model="formValue.controlRiskS" :min="1" style="width: 330px" />
        </el-form-item>
        <el-form-item label="风险值(R)" prop="controlRiskR">
          <el-input
            v-model="formValue.controlRiskR"
            size="large"
            disabled
            placeholder="自动计算: M×E×S"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item label="风险等级" prop="controlRiskLevel">
          <el-select v-model="formValue.controlRiskLevel" size="large" placeholder="请选择" style="width: 330px">
            <!-- <el-option label="A" value="A" />
            <el-option label="B" value="B" />
            <el-option label="C" value="C" /> -->
            <el-option label="D" value="D" />
          </el-select>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remarks" style="width: 87.2%">
          <el-input
            type="textarea"
            v-model="formValue.remarks"
            size="large"
            :rows="7"
            placeholder="例如：需每月提交检查报告"
          />
        </el-form-item>
      </el-form>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="$router.push({ name: 'hazardManage' })">返回</el-button>
      <el-button type="primary" :loading="submiting" @click="handleSubmit">提交</el-button>
    </footer>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, nextTick } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { getAllDepartments } from '@/api/auth/dept';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';

  import {
    queryAvailableUserList,
    safetyHazardInventoryQueryDetail,
    safetyHazardInventoryUpdateHazard,
  } from '@/api/production-safety/responsibility-implementation';

  const router = useRouter();
  const route = useRoute();
  const formRef = ref<any>(null);
  const submiting = ref(false);

  const userOptions = ref<any[]>([]);
  const firstLevelDepts = ref<any[]>([]);
  const cascaderProp = {
    expandTrigger: 'click',
    checkStrictly: true,
    value: 'id',
    label: 'deptName',
  };
  const cascaderRef = ref<any>({});

  const formValue = reactive({
    hazardCode: '',
    keyProcessUnit: '',
    hazardName: '',
    isMajorHazard: undefined as number | undefined,
    hazardSource: '',
    involvedDepartment: '',
    riskManagementDept: '',
    // riskManagementDeptId: [] as number[],
    cooperationDept: '',
    // cooperationDeptId: [] as number[],
    possibleConsequences: '',
    inherentRiskM: undefined as number | undefined,
    inherentRiskE: undefined as number | undefined,
    inherentRiskS: undefined as number | undefined,
    inherentRiskR: 0, // 自动计算
    inherentRiskLevel: '',
    inherentRiskUpgrade: '',
    controlMeasures: '',
    controlMainDept: '',
    // controlMainDeptId: [] as number[],
    controlCoopDept: '',
    // controlCoopDeptId: [] as number[],
    completionDeadline: '',
    completionStatus: '',
    verificationStatus: '',
    controlRiskM: undefined as number | undefined,
    controlRiskE: undefined as number | undefined,
    controlRiskS: undefined as number | undefined,
    controlRiskR: 0,
    controlRiskLevel: '',
    remarks: '',
  });

  const rules = reactive({
    hazardCode: [{ required: true, message: '请输入危险源编号', trigger: 'blur' }],
    keyProcessUnit: [{ required: true, message: '请输入关键工艺单元', trigger: 'blur' }],
    hazardName: [{ required: true, message: '请输入危险源名称', trigger: 'blur' }],
    isMajorHazard: [{ required: true, message: '请选择是否重大危险源', trigger: 'change' }],
    hazardSource: [{ required: true, message: '请输入危险源来源', trigger: 'blur' }],
    involvedDepartment: [{ required: true, message: '请输入涉及部门', trigger: 'blur' }],
    riskManagementDept: [{ required: true, message: '请选择风险管理部门', trigger: 'change' }],
    cooperationDept: [{ required: true, message: '请选择协作部门', trigger: 'change' }],
    possibleConsequences: [{ required: true, message: '请输入可能后果', trigger: 'blur' }],
    inherentRiskM: [{ required: true, message: '请选择可能性', trigger: 'change' }],
    inherentRiskE: [{ required: true, message: '请选择暴露频率', trigger: 'change' }],
    inherentRiskS: [{ required: true, message: '请选择严重度', trigger: 'change' }],
    inherentRiskLevel: [{ required: true, message: '请选择风险等级', trigger: 'change' }],
    controlMeasures: [{ required: true, message: '请输入管控措施', trigger: 'blur' }],
    controlMainDept: [{ required: true, message: '请选择主责部门', trigger: 'change' }],
    controlRiskM: [{ required: true, message: '请选择剩余风险可能性', trigger: 'change' }],
    controlRiskE: [{ required: true, message: '请选择剩余风险暴露频率', trigger: 'change' }],
    controlRiskS: [{ required: true, message: '请选择剩余风险严重度', trigger: 'change' }],
    controlRiskLevel: [{ required: true, message: '请选择剩余风险等级', trigger: 'change' }],
  });

  const handleChangeDept = (prop) => {
    const cascader = cascaderRef.value?.[prop];
    const deptInfo = cascader?.getCheckedNodes();
    formValue[prop] = deptInfo[0]?.label;
    formRef.value.validateField(prop);

    // nextTick(() => {
    //   handleQueryAvailableUserList(deptInfo[0].label, prop);
    // });
  };

  const getDeptData = () => {
    getAllDepartments().then((res) => {
      firstLevelDepts.value = formatDeptTree(res);
    });
  };

  const handleQueryAvailableUserList = (deptName, realname = '') => {
    queryAvailableUserList({
      pageNumber: 1,
      pageSize: 200,
      queryParam: {
        deptName,
        realname,
      },
    }).then((res: any) => {
      userOptions.value = (res.records || []).map((u: any) => ({
        value: u.userId || u.id,
        label: u.realname,
      }));
    });
  };
  const loadDetailData = (id: number) => {
    safetyHazardInventoryQueryDetail(id).then((res: any) => {
      Object.keys(formValue).forEach((key) => {
        if (res[key] !== undefined) {
          formValue[key] = res[key];
          // formValue['responsibleDepartmentId'] = res['responsibleDepartmentId']
          //   ? res['responsibleDepartmentId'].split(',').map((item: string) => Number(item))
          //   : [];
        }
      });
    });
  };
  // const getUserData = () => {
  //   getUserList({ pageNumber: 1, pageSize: 200, queryParam: {} }).then((res: any) => {
  //     userOptions.value = (res.records || []).map((u: any) => ({
  //       id: u.userId || u.id,
  //       name: u.realName || u.username,
  //     }));
  //   });
  // };

  onMounted(() => {
    getDeptData();
    handleQueryAvailableUserList('');
    loadDetailData(Number(route.query.id as unknown as number));
    // getUserData();
  });

  const handleSubmit = () => {
    formRef.value?.validate((valid: boolean) => {
      if (valid) {
        submiting.value = true;
        safetyHazardInventoryUpdateHazard({
          ...formValue,
          id: route.query.id,
        })
          .then(() => {
            ElMessage.success('创建成功!');
            router.push({ name: 'hazardManage' });
          })
          .finally(() => {
            submiting.value = false;
          });
      }
    });
  };
</script>
<style lang="scss" scoped>
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  .editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-right: 20px;
    overflow: hidden;

    // :deep(.w-e-text-container) {
    //   min-height: 400px;
    //   overflow-y: auto;
    // }
  }
  // :deep(.breadcrumb .title) {
  //   margin-left: 0;
  // }

  // .main {
  //   display: flex;
  //   flex-direction: column;
  //   padding: 20px;
  //   flex: 1;
  //   overflow: hidden;
  //   background-color: #fff;
  // }
  // .button-content {
  //   margin-bottom: 20px;
  // }

  // .page-content {
  //   display: flex;
  //   justify-content: flex-end;
  // }
  // // :deep(.el-form) {
  // //   flex: 1;
  // //   overflow: hidden;
  // //   overflow-y: auto;
  // // }
</style>
