<template>
  <my-dialog
    :visible="visible"
    :header="title"
    :width="670"
    attach="body"
    :closeOnOverlayClick="false"
    top="10vh"
    @close="emit('update:visible', false)"
  >
    <t-form ref="formRef" :data="formData" :rules="rules" label-width="80px">
      <t-form-item label="服务单元" name="serviceUnitId">
        <select-service-unit
          v-model="formData.serviceUnitId"
          :filterParams="{
            statusList: ['PUBLISH'],
          }"
        >
        </select-service-unit>
      </t-form-item>
      <t-form-item label="大区" name="regionName">
        <t-input v-model="formData.regionName" />
      </t-form-item>
      <t-form-item label="大区经理" name="leadId">
        <select-type-user v-model="formData.leadId" type="REGION_MANAGER">
        </select-type-user>
      </t-form-item>
      <t-form-item label="区域" name="targetValue" requiredMark>
        <div style="height: 400px">
          <t-transfer
            v-if="visible"
            v-model="targetValue"
            v-model:checked="checkedRef"
            :data="areaData"
            search
            @checked-change="handleCheckedChange"
          >
            <template #tree="slotProps">
              <t-tree v-bind="slotProps" checkable hover />
            </template>
          </t-transfer>
        </div>
      </t-form-item>
    </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="AddRegionDialog">
import { ref, computed, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import useClearDialog from '@/hooks/useClearDialog';
import { serviceRegionEditApi } from '@/api/service-unit';
import { buildData } from '@/components/common/select-area/area';

const emit = defineEmits(['update:visible']);
const formRef = ref(null);

const { areaData, areaCodeMap } = buildData(2);
const checkedRef = ref([]);
const targetValue = ref([]);

const props = defineProps({
  visible: Boolean,
  curRow: Object,
});

const title = computed(() => {
  return (isEdit.value ? '编辑' : '新增') + '大区';
});

const initFormData = {
  serviceRegionId: null,
  regionName: '',
  serviceUnitId: '',
  leadId: '',
};

const { formData, isEdit } = useClearDialog(
  initFormData,
  props,
  formRef,
  () => {
    for (let key in initFormData) {
      formData[key] = props.curRow[key];
    }
    targetValue.value = props.curRow.areaDtoList.map((item) => {
      const codes = areaCodeMap[`${item.province}_${item.city}`].split('_');
      return codes[1];
    });
  }
);

const rules = {
  serviceUnitId: [
    {
      required: true,
      message: '服务单元必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  regionName: [
    {
      required: true,
      message: '大区必填',
      type: 'error',
      trigger: 'change',
    },
  ],
  leadId: [
    {
      required: true,
      message: '大区经理必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  targetValue: [
    {
      validator: () => {
        if (!targetValue.value || !targetValue.value.length)
          return { result: false, message: '请完成区域设置' };

        return { result: true, type: 'success' };
      },
      type: 'error',
      trigger: 'change',
    },
  ],
};

const handleCheckedChange = ({ checked }) => {
  checkedRef.value = checked;
};

const save = async () => {
  const valid = await formRef.value.validate();
  if (valid !== true) return;

  let data = { ...formData };
  data.areaDtoList = targetValue.value.map((item) => {
    return {
      province: areaCodeMap[item.substring(0, 2)],
      address: '',
      area: '',
      country: '中国',
      city: areaCodeMap[item],
    };
  });

  let result = true;
  await serviceRegionEditApi(data).catch(() => {
    result = false;
  });
  if (!result) return;

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

watch(
  () => props.visible,
  (val) => {
    if (!val) {
      targetValue.value = [];
    }
  }
);
</script>

<style lang="less" scoped>
.t-transfer {
  :deep(.t-transfer__list) {
    width: 240px;
  }
}
</style>
