<template>
  <el-dialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    title="下发安全责任书"
    width="700"
    @close="clearData"
  >
    <el-form label-width="auto" :model="formData" ref="ruleFormRef" :rules="rules">
      <el-form-item label="下发部门名称" prop="deptId">
        <!-- :disabled="currentDepartmentKey === 'A'" -->

        <el-cascader
          ref="cascaderRef"
          style="width: 100%"
          size="large"
          v-model="formData.deptId"
          :options="departmentOptions"
          :props="cascaderProp"
          :show-all-levels="false"
          placeholder="请选择下发部门"
          :clearable="false"
        />
      </el-form-item>
      <!-- 如果是院领导直接选择人，不用选分组 -->
      <el-form-item label="选择部门下的人员" prop="userIds" v-if="currentRowData.departmentName === '院领导'">
        <!-- <el-select
          multiple
          size="large"
          v-model="formData.userIds"
          placeholder="请选择部门下的人员"
          style="width: 100%"
        >
          <el-option
            v-for="group in groupList"
            :disabled="originUserGroupId.includes(group.id)"
            :key="group.id"
            :label="group.name"
            :value="group.id"
          />
        </el-select> -->
        <el-select
            size="large"
            v-model="formData.userIds"
            placeholder="请选择部门下的人员"
            style="width: 100%"
            filterable
            multiple
            remote
            :remote-method="(q) => remoteMethod(q, 'leader1List')">
            <el-option v-for="l in userList.leader1List" :key="l.value" :label="l.label" :value="l.value" />
          </el-select>
      </el-form-item>

      <el-form-item label="下发分组名称" prop="userGroupId"  v-else>
        <el-row style="width:100%" :gutter="12">
            <el-col :span="16">
              <el-select
                multiple
                size="large"
                v-model="formData.userGroupId"
                placeholder="请选择下发分组"
                >
                <el-option
                    v-for="group in groupList"
                    :disabled="originUserGroupId.includes(group.id)"
                    :key="group.id"
                    :label="group.name"
                    :value="group.id"
                />
                </el-select>
            </el-col>
            <el-col :span="8">
                <el-button link type="primary" @click="reviewStaffData">查看人员详情</el-button>
            </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="多人签署设置" prop="signConfig" v-if="currentDepartmentKey === 'B'">
        <el-radio-group v-model="formData.signConfig">
          <el-radio :value="0">否</el-radio>
          <el-radio :value="1">是</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="签署人顺序设置" prop="signPerson" v-if="formData.signConfig === 1">
        <el-select
          size="large"
          multiple
          v-model="formData.signPerson"
          placeholder="请选择顺序"
          style="width: 100%"
          remote
          filterable
          :remote-method="(q) => remoteMethod(q, 'signPersonList')"
        >
          <el-option v-for="l in userList.signPersonList" :key="l.value" :label="l.label" :value="l.value" />
        </el-select>
      </el-form-item>
      <template v-if="currentDepartmentKey === 'A'">
        <el-form-item label="党委书记" prop="leader1">
          <el-select
            size="large"
            v-model="formData.leader1"
            placeholder="请选择党委书记"
            style="width: 100%"
            filterable
            remote
            :remote-method="(q) => remoteMethod(q, 'leader1List')"
          >
            <el-option v-for="l in userList.leader1List" :key="l.value" :label="`${l.label}（${l.staffNo}）`" :value="l.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="院长" prop="leader2">
          <el-select
            size="large"
            v-model="formData.leader2"
            placeholder="请选择院长"
            style="width: 100%"
            filterable
            remote
            :remote-method="(q) => remoteMethod(q, 'leader2List')"
          >
            <el-option v-for="l in userList.leader2List" :key="l.value" :label="`${l.label}（${l.staffNo}）`" :value="l.value" />
          </el-select>
        </el-form-item>
      </template>
      <template v-if="currentDepartmentKey === 'B'">
        <el-form-item label="党委书记" prop="leader1">
          <el-select
            size="large"
            v-model="formData.leader1"
            placeholder="请选择党委书记"
            style="width: 100%"
            filterable
            remote
            :remote-method="(q) => remoteMethod(q, 'leader1List')"
          >
            <el-option v-for="l in userList.leader1List" :key="l.value" :label="`${l.label}（${l.staffNo}）`" :value="l.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="院长" prop="leader2">
          <el-select
            size="large"
            v-model="formData.leader2"
            placeholder="请选择院长"
            style="width: 100%"
            filterable
            remote
            :remote-method="(q) => remoteMethod(q, 'leader2List')"
          >
            <el-option v-for="l in userList.leader2List" :key="l.value" :label="`${l.label}（${l.staffNo}）`" :value="l.value" />
          </el-select>
        </el-form-item>
      </template>
      <!-- <template v-if="currentDepartmentKey === 'C'">
        <el-form-item label="党委书记" prop="leader1">
          <el-select
            size="large"
            v-model="formData.leader1"
            placeholder="请选择党委书记"
            style="width: 100%"
            filterable
            :remote-method="(q) => remoteMethod(q, 'leader1List')"
            remote
          >
            <el-option v-for="l in userList.leader1List" :key="l.value" :label="l.label" :value="l.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="所长/部长" prop="leader2">
          <el-select
            size="large"
            v-model="formData.leader2"
            placeholder="请选择所长/部长"
            style="width: 100%"
            filterable
            :remote-method="(q) => remoteMethod(q, 'leader2List')"
            remote
          >
            <el-option v-for="l in userList.leader2List" :key="l.value" :label="l.label" :value="l.value" />
          </el-select>
        </el-form-item>
      </template> -->
      <!-- <template v-if="currentDepartmentKey === 'D'">
        <el-form-item label="部门负责人" prop="leader1">
          <el-select
            size="large"
            v-model="formData.leader1"
            placeholder="部门负责人"
            style="width: 100%"
            filterable
            :remote-method="(q) => remoteMethod(q, 'leader1List')"
            remote
          >
            <el-option v-for="l in userList.leader1List" :key="l.value" :label="l.label" :value="l.value" />
          </el-select>
        </el-form-item>
      </template> -->

      <el-form-item label="计划开始日期" prop="planStartTime">
        <el-date-picker
          size="large"
          style="width: 100%"
          v-model="formData.planStartTime"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          placeholder="开始日期"
        />
      </el-form-item>

      <el-form-item label="计划结束日期" prop="planEndTime">
        <el-date-picker
          size="large"
          style="width: 100%"
          v-model="formData.planEndTime"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          placeholder="结束日期"
        />
      </el-form-item>

      <el-form-item label="是否推送" prop="isUrgent">
        <el-radio-group v-model="formData.isUrgent">
          <el-radio :value="0">否</el-radio>
          <el-radio :value="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" :loading="submitLoading" @click="submitForm"> 保存 </el-button>
      <el-button @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="staffDialogVisible" width="70%" title="查看分组人员详情" @close="handleRestParams">
    <div class="search-form">
        <el-form :inline="true">
          <el-form-item>
            <el-input
              v-model="tableQuery.queryParam.keyword"
              placeholder="搜索工号/姓名/分组名称"
              style="width: 170px"
            />
          </el-form-item>
          <el-form-item>
            <el-cascader
                ref="cascaderRef"
                style="width: 100%"
                size="large"
                v-model="tableQuery.queryParam.deptId"
                :options="firstLevelDepts"
                :props="deptProp"
                :show-all-levels="false"
                placeholder="请选择部门"
                :clearable="false"
                @change="handleDeptChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleRestParams">重置</el-button>
          </el-form-item>
        </el-form>
        
      </div>

    <h4 style="margin:10px 0" v-if="messages">{{ messages.toString() }}</h4>
    <div class="batch-table">
        <BasicTable
        ref="basicTableRef"
        :tableData="staffTableData"
        :tableConfig="tableConfig"
        @update:pageSize="handleSizeChange"
        @update:pageNumber="handleCurrentChange"
        >
        </BasicTable>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, watch, onMounted } from 'vue';
  import { ElMessage, type FormInstance } from 'element-plus';
  import dayjs from 'dayjs';
  import { uniqWith, isEqual } from 'lodash-es';
  import {
    queryAvailableUserList,
    safetyResponsibilityAdminQueryDetail,
    queryUserByGroupIds
  } from '@/api/production-safety/responsibility-implementation';
  import {STAFF_TABLE_COLUMNS, TABLE_OPTIONS} from "../config/table"
  import type { QueryPageRequest } from '@/types/basic-query';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import BasicTable from '@/components/BasicTable.vue';
  import { getAllDepartments } from '@/api/auth/dept';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';

  // 表格
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(STAFF_TABLE_COLUMNS, TABLE_OPTIONS);

  const props = defineProps<{
    modelValue: boolean;
    currentDepartmentKey: string;
    groupList: any[];
    departmentOptions: any[];
    currentRowData: any;
  }>();

  const emit = defineEmits(['close', 'submit', 'update:modelValue']);
  const submitLoading = ref(false);
  const staffDialogVisible = ref(false);
  const staffTableData = ref<any[]>([]);
  const ruleFormRef = ref<FormInstance>();
  const cascaderRef = ref<any>();
  const userList = reactive<{
    [key: string]: any[];
  }>({
    signPersonList: [],
    leader1List: [],
    leader2List: [],
  });

  const formData = reactive<any>({
    signConfig: 0,
    userIds: [],
    userGroupId: [],
    signPerson: [],
    leader1: null,
    leader2: null,
    planStartTime: null,
    planEndTime: null,
    isUrgent: 0,
    deptId: [],
  });

  const tableQuery = reactive<QueryPageRequest<any>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
        userGroupIds: [], // 用户分组
        keyword: '',// 支持搜索工号，姓名，分组名称
        deptName: undefined,// 部门
        deptId: undefined // 部门id 
    },
  });

  const cascaderProp = {
    expandTrigger: 'click',
    checkStrictly: props.currentDepartmentKey === 'default',
    value: 'id',
    label: 'deptName',
    multiple: !/A|B/.test(props.currentDepartmentKey),
    disabled: (data, node) => {
      return originDeptId.value.some((path) => isEqual(path, node.pathValues));
    },
  };
  const firstLevelDepts = ref<any[]>([]);
  const deptProp = {
    expandTrigger: 'click',
    checkStrictly: true,
    // emitPath: false,
    value: 'id',
    label: 'deptName',
  };
  const getDeptData = () => {
    getAllDepartments().then((res) => {
      firstLevelDepts.value = formatDeptTree(res);
    });
  };
  const handleDeptChange = () => {
  const nodes = cascaderRef.value?.getCheckedNodes();
  
  if (nodes && nodes.length > 0) {
    // 当前选中的【唯一节点】
    const currentDept = nodes[0];
    tableQuery.queryParam.deptId = currentDept.value
    // tableQuery.queryParam.deptName = currentDept.label
    // console.log('✅ 当前选中部门完整数据：', currentDept.data); 
    // console.log('ID：', currentDept.value);
    // console.log('名称：', currentDept.label);
  }
};
  watch(
    () => [props.currentDepartmentKey, props.departmentOptions],
    ([currentDepartmentKey, departmentOptions]) => {
      if (!currentDepartmentKey) return;
      // 针对院领导的特殊处理
      // if (currentDepartmentKey === 'A' && Array.isArray(departmentOptions) && departmentOptions.length) {
      //   const id = departmentOptions.find((d) => d.deptName === '院领导')?.id;
      //   formData.deptId = [id];
      // }
      //   console.log('departmentOptions:', departmentOptions);
      formData.leader1 = null;
      formData.leader2 = null;
      formData.signPerson = [];
      getUserData(null, '');
    },
    {
      immediate: true,
    },
  );
  const originDeptId = ref<any>([]);
  const originUserGroupId = ref<any>([]);
  onMounted(() => {
    safetyResponsibilityAdminQueryDetail({
      id: props.currentRowData.id,
    }).then((res) => {
      console.log('res:', res);
      for (let key in res) {
        formData[key] = res[key];
        Object.assign(formData, {
          [key]: res[key],
          deptId: res.deptId ? JSON.parse(res.deptId) : [],
          userGroupId: res.userGroupId ? res.userGroupId.split(',').map((id) => Number(id)) : [],
        });
        originDeptId.value = res.deptId ? JSON.parse(res.deptId) : [];
        originUserGroupId.value = res.userGroupId ? res.userGroupId.split(',').map((id) => Number(id)) : [];
      }
      console.log('formData:', formData);
    });
  });

  const handleClose = () => {
    emit('update:modelValue', false);
    clearData();
  };

  const remoteMethod = (query: string, dataName) => {
    // if (!query) return;
    getUserData(dataName, query);
  };
  
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableData();
  };
    const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };
  const messages = ref([])
  async function getTableData() {
    tableConfig.loading = true;
    try {
      tableQuery.queryParam.userGroupIds =  formData.userGroupId
      const res = await queryUserByGroupIds(tableQuery);
      if (res) {
        // 映射返回数据字段到表格字段
        messages.value = res.messages
        staffTableData.value = res.pages.records;
        pagination.total = res.pages.totalRow;
      }else{
        staffTableData.value = [];
        messages.value = []
        pagination.total = 0;
      }
    } catch (e) {
      staffTableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };
  const handleRestParams = async ()=>{
  pagination.pageNumber = 1;
  pagination.pageSize = 10
  Object.assign(tableQuery, {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
        userGroupIds: formData.userGroupId,
        keyword: undefined,
        deptName: undefined,
        deptId: undefined
    }
  })
  await getTableData();
  }
  const reviewStaffData = async ()=>{
    console.log(formData.userGroupId, formData.userGroupId.length)
    if(formData.userGroupId.length === 0){
        ElMessage.error('请先选择分组')
        return
    }
    staffDialogVisible.value = true
    await getDeptData();
    await getTableData();
  }
  // const handleRemoveTag = (val, field, originData) => {
  //   console.log('has:', originData, val);

  //   const currentId = new Set(originData.flat());
  //   const has = Array.isArray(val) ? val.every((v) => currentId.has(v)) : currentId.has(val);
  //   if (has) {
  //     ElMessage.error('不能删除已有下发部门');
  //     formData[field] = [...originData, ...uniqWith(formData[field], isEqual)];
  //     return;
  //   }
  // };

  const rules = reactive({
    deptId: [{ required: true, message: '请选择下发部门', trigger: 'change' }],
    userGroupId: [{ required: true, message: '请选择下发分组', trigger: 'change' }],
    userIds:[{ required: true, message: '请选择部门下的人员', trigger: 'change' }],
    signOrder: [
      {
        validator: (_: any, value: any, callback: any) => {
          if (formData?.signPerson === 1 && (!value || value.length === 0)) {
            return callback(new Error('请选择签署人顺序'));
          }
          callback();
        },
        trigger: 'change',
      },
    ],

    leader1: [{ required: true, message: '请选择相关责任负责人/领导', trigger: 'change' }],

    leader2: [
      { required: true, message: '请选择相关责任负责人/领导', trigger: 'change' },
      {
        validator: (_: any, value: any, callback: any) => {
          const needLeader2 = ['A', 'B', 'C'].includes(props.currentDepartmentKey);
          if (needLeader2 && !value) {
            return callback(new Error('请选择对应的院长/部长/负责人'));
          }
          callback();
        },
        trigger: 'change',
      },
    ],

    planStartTime: [
      { required: true, message: '请选择开始日期', trigger: 'change' },
      {
        validator: (_: any, value: any, callback: any) => {
          if (value && formData.planEndTime) {
            if (dayjs(value).isAfter(dayjs(formData.planEndTime))) {
              return callback(new Error('开始日期不能晚于结束日期'));
            }
          }
          callback();
        },
        trigger: 'change',
      },
    ],

    planEndTime: [
      { required: true, message: '请选择结束日期', trigger: 'change' },
      {
        validator: (_: any, value: any, callback: any) => {
          if (value && formData.planStartTime) {
            if (dayjs(value).isBefore(dayjs(formData.planStartTime))) {
              return callback(new Error('结束日期不能早于开始日期'));
            }
          }
          callback();
        },
        trigger: 'change',
      },
    ],
  });

  function getUserData(dataName, realname = '') {
    queryAvailableUserList({
      pageNumber: 1,
      pageSize: 500,
      queryParam: { realname },
    }).then((res: any) => {
      if (dataName === null) {
        Object.keys(userList).forEach((key) => {
          userList[key] = (res.records || [])?.map((u: any) => ({
            value: u.id,
            label: u.realname,
            staffNo: u.staffNo
          }));
        });
      } else {
        userList[dataName] = (res.records || [])?.map((u: any) => ({
          value: u.id,
          label: u.realname,
          staffNo: u.staffNo
        }));
      }
    });
  }

  function clearData() {
    ruleFormRef.value?.resetFields();
    Object.assign(formData, {
      signConfig: 0,
      userIds: [],
      userGroupId: [],
      signPerson: [],
      leader1: null,
      leader2: null,
      planStartTime: null,
      planEndTime: null,
      isUrgent: 0,
    });
  }

  async function submitForm() {
    if (!ruleFormRef.value) return;
    await ruleFormRef.value.validate((valid) => {
      if (valid) {
        emit('submit', { ...formData }, submitLoading);
      }
    });
  }
</script>

<style scoped lang="scss">
.flex {
    display: flex;
    gap: 6px;
}
.align-center {
    align-items: center;
}

</style>
