<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="服务单元"
            >{{ requestInfo.serviceUnitName }}
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="项目单号">{{ requestInfo.crmNo }} </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="客户类型"
            >{{ customerTypeFilter(requestInfo.customType) }}
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="客户名称"
            >{{ requestInfo.customName }}
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="服务档位">{{ requestInfo.level }} </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="客户地址">
            <t-space>
              <span>
                <span>{{ requestInfo.customProvince }}</span>
                <span>{{ requestInfo.customCity }}</span>
                <span>{{ requestInfo.customArea }}</span>
              </span>
              <span>{{ requestInfo.customAddress }}</span>
            </t-space>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="人员调配" labelAlign="top">
            <div>
              <t-table
                size="small"
                row-key="roleId"
                :columns="roleColumns"
                :data="tableData"
                bordered
              >
                <template #roleName="{ row }">
                  <span v-if="row.roleName === '区域协调人'">
                    <span style="color: red" v-if="IS_CLOUD">* </span>
                    {{ row.roleName }}</span
                  >
                  <span v-else
                    ><span style="color: red">* </span>{{ row.roleName }}</span
                  >
                </template>
                <template #key="{ row }">
                  <t-select
                    v-if="row.key === 'REGION_COORDINATOR'"
                    v-model="formData.allocationParams[0].userIdList"
                    :options="options1"
                    placeholder="请选择"
                    multiple
                    :max="1"
                    :keys="{ label: 'str', value: 'userId' }"
                    filterable
                  />
                  <t-select
                    v-if="row.key === 'PROJECT_MANAGER'"
                    v-model="formData.allocationParams[1].userIdList"
                    :options="options2"
                    placeholder="请选择"
                    multiple
                    :max="1"
                    :keys="{ label: 'str', value: 'userId' }"
                    filterable
                  />
                  <t-select
                    v-if="row.key === 'ENGINEER'"
                    v-model="formData.allocationParams[2].userIdList"
                    :options="options3"
                    placeholder="请选择"
                    multiple
                    :keys="{ label: 'str', value: 'userId' }"
                    filterable
                  />
                </template>
                <template #history="{ row }">
                  {{ buildHistoryStr(row.history) }}
                </template>
              </t-table>
            </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="AllocationDialog">
import { computed, onMounted, ref, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { MinusCircleFilledIcon } from 'tdesign-icons-vue-next';
import {} from '@/api/resource-guard';
import { customerTypeFilter } from '@/utils/filter';
import { cloneDeep } from 'lodash-es';
import {
  getAllocationInfoApi,
  saveAllocationInfoApi,
} from '@/api/service-unit';
import { saveAllocationApi } from '@/api/sop';
import useClearDialog from '@/hooks/useClearDialog';

const buildHistoryStr = (arr) => {
  return arr
    .map((item) => `${item.name}_${item.supplierName}_${item.city}`)
    .join('、');
};

const emit = defineEmits(['update:visible', 'success']);
const props = defineProps({
  visible: Boolean,
  curRow: Object,
  fromSop: Boolean,
  isCloud: {
    type: Boolean,
    default: false,
  },
});
const requestInfo = ref({});
const formRef = ref(null);
const IS_CLOUD = computed(() => {
  return props.isCloud || props.curRow?.type === 'CLOUD_MARK_SOP_FLOW';
});
const init = () => {
  return [
    {
      sopRoleType: 'REGION_COORDINATOR',
      userIdList: [],
    },
    {
      sopRoleType: 'PROJECT_MANAGER',
      userIdList: [],
    },
    {
      sopRoleType: 'ENGINEER',
      userIdList: [],
    },
  ];
};
const { formData, isEdit } = useClearDialog(
  {
    crmDetailId: '',
    allocationParams: init(),
  },
  props,
  formRef,
  () => {
    formData.crmDetailId = props.fromSop
      ? props.curRow?.crmDetailId
      : props.curRow?.id; //两种场景使用了人员调配，一个是菜单页面的SOP列表，一个是创建sop里的sop列表
    formData.allocationParams = init();
    getOptions();
  }
);

const options1 = ref([]);
const options2 = ref([]);
const options3 = ref([]);
const getOptions = () => {
  getAllocationInfoApi({
    crmDetailId: props.fromSop ? props.curRow?.crmDetailId : props.curRow?.id,
  }).then((res) => {
    requestInfo.value = res;
    if (IS_CLOUD.value) {
      tableData.value[0].history = res.regionCoordinatorInfo.historicalList;
      tableData.value[1].history = res.projectManagerInfo.historicalList;
      tableData.value[2].history = res.engineerInfo.historicalList;
    } else {
      tableData.value[0].history = res.projectManagerInfo.historicalList;
      tableData.value[1].history = res.engineerInfo.historicalList;
    }

    options1.value = [...(res.regionCoordinatorInfo.canChooseList || [])].map(
      (item) => {
        item.str = `${item.supplierName}_${item.name}_${item.mobileNumber}`;
        return item;
      }
    );
    options2.value = [...(res.projectManagerInfo.canChooseList || [])].map(
      (item) => {
        item.str = `${item.supplierName}_${item.name}_${item.mobileNumber}`;
        return item;
      }
    );
    options3.value = [...(res.engineerInfo.canChooseList || [])].map((item) => {
      item.str = `${item.supplierName}_${item.name}_${item.mobileNumber}`;
      return item;
    });
    formData.allocationParams[0].userIdList = (
      res.regionCoordinatorInfo.allocatedList || []
    ).map((item) => item.userId);
    formData.allocationParams[1].userIdList = (
      res.projectManagerInfo.allocatedList || []
    ).map((item) => item.userId);
    formData.allocationParams[2].userIdList = (
      res.engineerInfo.allocatedList || []
    ).map((item) => item.userId);
  });
};

const tableData = IS_CLOUD.value
  ? ref([
      {
        roleName: '区域协调人',
        history: [],
        key: 'REGION_COORDINATOR',
      },
      {
        roleName: '项目经理',
        history: [],
        key: 'PROJECT_MANAGER',
      },
      {
        roleName: '工程师',
        history: [],
        key: 'ENGINEER',
      },
    ])
  : ref([
      {
        roleName: '项目经理',
        history: [],
        key: 'PROJECT_MANAGER',
      },
      {
        roleName: '工程师',
        history: [],
        key: 'ENGINEER',
      },
    ]);
const roleColumns = [
  { colKey: 'roleName', title: '角色', width: 120, cel: 'roleName' },
  { colKey: 'key', title: '人员', cell: 'key' },
  { colKey: 'history', title: '历史人员记录', cell: 'history', width: 200 },
];

const save = async () => {
  if (IS_CLOUD.value && !formData.allocationParams[0].userIdList?.length) {
    return MessagePlugin.error('区域协调人必选，且只能选择一个');
  } else if (!formData.allocationParams[1].userIdList?.length) {
    return MessagePlugin.error('大区经理必选，且只能选择一个');
  } else if (!formData.allocationParams[2].userIdList?.length) {
    return MessagePlugin.error('工程师必选');
  }
  if (props.fromSop) {
    saveAllocationApi({ ...formData, flowId: props.curRow?.flowId }).then(
      () => {
        MessagePlugin.success('保存成功');
        emit('update:visible', false);
        emit('success');
      }
    );
  } else {
    saveAllocationInfoApi(formData).then(() => {
      MessagePlugin.success('保存成功');
      emit('update:visible', false);
      emit('success');
    });
  }
};

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