<template>
  <my-dialog
    :visible="visible"
    header="调配"
    :width="800"
    attach="body"
    :closeOnOverlayClick="false"
    @close="emit('update:visible', false)"
    @opened="dialogOpened"
  >
    <t-form ref="formRef" :labelWidth="66" colon>
      <t-row :gutter="[20, 0]">
        <t-col :span="6">
          <t-form-item label="服务单元"
            >{{ formData.serviceUnitName }}
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="项目单号">{{ formData.crmNo }} </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="客户类型"
            >{{ customerTypeFilter(formData.customType) }}
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="客户名称">{{ formData.customName }} </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="服务档位">{{ formData.level }} </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="客户地址">
            <t-space>
              <span>{{ formData.province }}</span>
              <span>{{ formData.city }}</span>
              <span>{{ formData.area }}</span>
              <span>{{ formData.address }}</span>
            </t-space>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="人员调配" labelAlign="top">
            <div>
              <div style="text-align: right; height: 0">
                <div
                  style="display: inline-block; position: relative; top: -26px"
                >
                  <span
                    v-if="!curRow.regionManagerId"
                    style="vertical-align: top; font-size: 12px; color: #ff7d00"
                    >（尚未安排大区经理，请先安排大区经理后再勾选）</span
                  >
                  <t-checkbox
                    :disabled="!curRow.regionManagerId"
                    v-model="regionUseManage"
                    @change="regionUseManageChange"
                    >区域协调人由大区经理兼任</t-checkbox
                  >
                </div>
              </div>
              <t-table
                size="small"
                row-key="roleId"
                :columns="roleColumns"
                :data="formData.roleConfigInfo"
                bordered
              >
                <template #num="{ row }">
                  <div
                    :class="{
                      'color-error': row.userIdList.length > row.quota,
                    }"
                  >
                    <span>{{ row.userIdList.length }}</span>
                    <span>/</span>
                    <span>{{ row.quota }}</span>
                  </div>
                </template>
                <template #users="{ row }">
                  <select-free-engineer
                    v-model="row.userIdList"
                    :type="row.roleType"
                    :unit-id="curRow.serviceUnitId"
                    :crm-no="curRow.crmNo"
                    multiple
                    :min-collapsed-num="10"
                    :max="row.roleType === 'REGION_COORDINATOR' ? 1 : 0"
                  ></select-free-engineer>
                </template>
                <template #operate="{ row }">
                  <div class="table-operations">
                    <t-button
                      theme="danger"
                      shape="square"
                      variant="text"
                      @click="handleDelete(row)"
                    >
                      <template #icon> <MinusCircleFilledIcon /></template>
                    </t-button>
                  </div>
                </template>
              </t-table>
              <div
                class="flex justify-between items-center"
                style="width: 100%; margin-top: 16px"
              >
                <t-select v-model="selectedRoleId" @change="roleChange">
                  <t-option
                    v-for="item in roleList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                    :disabled="checkRoleDisabled(item)"
                  ></t-option>
                </t-select>
                <t-button
                  class="m-l-10px"
                  theme="primary"
                  :disabled="!selectedRole"
                  @click="toAddRole"
                  >添加</t-button
                >
              </div>
            </div>
          </t-form-item>
        </t-col>
      </t-row>
    </t-form>
    <template #foot>
      <t-button theme="default" @click="emit('update:visible', false)"
        >取消</t-button
      >
      <t-button theme="primary" @click="save">保存</t-button>
    </template>
  </my-dialog>
</template>
<script setup name="PersonDeployDialog">
import { computed, onMounted, ref, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { MinusCircleFilledIcon } from 'tdesign-icons-vue-next';
import useClearDialog from '@/hooks/useClearDialog';
import useAuthenRole from '@/hooks/useAuthenRole';
import {
  personAllocateDeployApi,
  personAllocateRoleDetailApi,
} from '@/api/resource-guard';
import { customerTypeFilter } from '@/utils/filter';
import { cloneDeep } from 'lodash';

const emit = defineEmits(['update:visible', 'success']);
const props = defineProps({
  visible: Boolean,
  curRow: Object,
});
const regionUseManage = ref(false);
watch(
  () => props.visible,
  (val) => {
    if (!val) {
      regionUseManage.value = false;
    }
  }
);
const regionUseManageChange = () => {
  let allData = JSON.parse(JSON.stringify(roleConfigInfoAllData.value));

  if (regionUseManage.value) {
    // formData.roleConfigInfo = formData.roleConfigInfo.filter(
    //   (item) => item.roleType !== 'REGION_COORDINATOR'
    // );
    formData.roleConfigInfo = allData.filter(
      (item) => item.roleType !== 'REGION_COORDINATOR'
    );
  } else {
    formData.roleConfigInfo = allData;
  }
  selectedRoleId.value = null;
  selectedRole.value = null;
};

const configRoleIds = computed(() => {
  return formData.roleConfigInfo.map((item) => item.roleId);
});

const checkRoleDisabled = (item) => {
  if (item.type === 'REGION_COORDINATOR' && regionUseManage.value) return true;
  return configRoleIds.value.includes(item.id);
};

const formRef = ref(null);
let selectedRole = ref(null);
let selectedRoleId = ref(null);

const { roleList, getRoleList } = useAuthenRole();

const getDetail = async () => {
  for (let key in formData) {
    formData[key] = props.curRow[key];
  }
  formData.roleConfigInfo = formData.roleConfigInfo || [];

  const res = await personAllocateRoleDetailApi(props.curRow.crmNo).catch(
    () => {}
  );
  if (!res) return;

  const roleQuota = {
    REGION_COORDINATOR: props.curRow.coordinatorQuota,
    EFFECT_ENGINEER: props.curRow.effectQuota,
    ASSISTANT_ENGINEER: props.curRow.assistantQuota,
  };
  if (res.length) {
    let roleConfigMap = {};

    res.forEach((item) => {
      if (!roleConfigMap[item.roleResult.roleId]) {
        roleConfigMap[item.roleResult.roleId] = {
          quota: roleQuota[item.roleResult.roleType],
          userIdList: [],
          ...item.roleResult,
        };
      }
      roleConfigMap[item.roleResult.roleId].userIdList.push(item.userId);
    });
    const validRoleTypes = Object.keys(roleQuota).filter(
      (item) => roleQuota[item]
    );
    let singleList = cloneDeep(roleList.value)
      .filter(
        (item) =>
          validRoleTypes.includes(item.type) &&
          item.type === 'REGION_COORDINATOR'
      )
      .map((item) => {
        return {
          quota: roleQuota[item.type],
          userIdList: [],
          roleId: item.id,
          roleName: item.name,
          roleType: item.type,
        };
      });
    console.log('singleList:', singleList);
    console.log('roleConfigMap:', roleConfigMap);
    let arr = Object.values(roleConfigMap);
    let rId = singleList[0]?.roleId;
    formData.roleConfigInfo = [
      ...(arr.find((item) => item.roleId == rId) ? [] : singleList),
      ...arr,
    ];
  } else {
    const validRoleTypes = Object.keys(roleQuota).filter(
      (item) => roleQuota[item]
    );
    formData.roleConfigInfo = roleList.value
      .filter((item) => validRoleTypes.includes(item.type))
      .map((item) => {
        return {
          quota: roleQuota[item.type],
          userIdList: [],
          roleId: item.id,
          roleName: item.name,
          roleType: item.type,
        };
      });
  }
  roleConfigInfoAllData.value = JSON.parse(
    JSON.stringify(formData.roleConfigInfo)
  );
  const regionUserInfo = formData.roleConfigInfo.find(
    (item) => item.roleType === 'REGION_COORDINATOR'
  );
  if (
    (regionUserInfo &&
      regionUserInfo.userIdList[0] === props.curRow.regionManagerId) ||
    props.curRow.concurrently
  ) {
    regionUseManage.value = true;
    regionUseManageChange();
  }
};

const roleConfigInfoAllData = ref([]);

const { formData } = useClearDialog(
  {
    id: null,
    serviceUnitId: null,
    serviceUnitName: '',
    crmNo: '',
    customName: '',
    customType: '',
    province: '',
    city: '',
    area: '',
    level: '',
    roleConfigInfo: [],
  },
  props,
  formRef,
  getDetail
);

const roleColumns = [
  { colKey: 'roleName', title: '项目角色', width: 120 },
  { colKey: 'quota', title: '配额', cell: 'num', width: 80, align: 'center' },
  { colKey: 'users', title: '人员', cell: 'users' },
  { colKey: 'operate', title: '', cell: 'operate', width: 60 },
];

const dialogOpened = () => {
  selectedRole.value = null;
  selectedRoleId.value = null;
};

const roleChange = () => {
  selectedRole.value = roleList.value.find(
    (item) => item.id === selectedRoleId.value
  );
};
const sortRole = () => {
  const roleIndexs = {
    REGION_COORDINATOR: 1,
    EFFECT_ENGINEER: 2,
    ASSISTANT_ENGINEER: 3,
  };
  formData.roleConfigInfo.sort(
    (a, b) => roleIndexs[a.roleType] - roleIndexs[b.roleType]
  );
};

const toAddRole = () => {
  if (
    formData.roleConfigInfo.some(
      (item) => item.roleId === selectedRole.value.id
    )
  ) {
    MessagePlugin.error('当前角色已经被选过！');
    return;
  }

  formData.roleConfigInfo.push({
    quota: 1,
    userIdList: [],
    roleId: selectedRole.value.id,
    roleName: selectedRole.value.name,
    roleType: selectedRole.value.type,
  });
  sortRole();

  selectedRole.value = null;
  selectedRoleId.value = null;
};
const handleDelete = (row) => {
  formData.roleConfigInfo = formData.roleConfigInfo.filter(
    (item) => item.roleId !== row.roleId
  );
  roleConfigInfoAllData.value = roleConfigInfoAllData.value.filter(
    (item) => item.roleId !== row.roleId
  );
};

const checkRoleList = () => {
  const val = formData.roleConfigInfo;
  // if (!val || !val.length)
  //   return { result: false, message: '至少配置一个角色' };

  if (val.some((item) => !item.userIdList.length))
    return { result: false, message: '有角色未设置人员' };

  return { result: true, type: 'success' };
};
const save = async () => {
  const checkResult = checkRoleList();
  if (!checkResult.result) {
    MessagePlugin.error(checkResult.message);
    return;
  }

  let data = {
    serviceUnitId: formData.serviceUnitId,
    crmNo: formData.crmNo,
    allocationParams: formData.roleConfigInfo
      .filter((item) => item.roleType !== 'REGION_COORDINATOR')
      .map((item) => {
        return {
          roleId: item.roleId,
          userIdList: item.userIdList,
        };
      }),
  };

  if (regionUseManage.value) {
    data.regionUserId = props.curRow.regionManagerId;
  } else {
    const regionUserInfo = formData.roleConfigInfo.find(
      (item) => item.roleType === 'REGION_COORDINATOR'
    );
    if (regionUserInfo) data.regionUserId = regionUserInfo.userIdList[0];
  }

  const res = await personAllocateDeployApi(data).catch(() => {});
  if (!res) return;

  MessagePlugin.success('保存成功');
  emit('update:visible', false);
  emit('success');
};

onMounted(() => {
  getRoleList();
});
</script>
