<template>
  <my-dialog
    :visible="visible"
    :header="dialogTitle"
    :width="dialogWidth"
    attach="body"
    :closeOnOverlayClick="false"
    @close="emit('update:visible', false)"
    @opened="onOpened"
  >
    <slot></slot>
    <t-form ref="formRef" :data="formData" :rules="rules" :labelWidth="100">
      <t-row :gutter="[0, 20]">
        <t-col :span="12">
          <t-form-item label="服务单元" name="serviceUnitId">
            <select-service-unit
              v-if="visible"
              v-model="formData.serviceUnitId"
              :filterParams="{
                statusList: ['PUBLISH'],
                type: customType,
              }"
            >
            </select-service-unit>
          </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="MultDelineationDialog">
import { ref, reactive } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { serviceScopeBindBatchApi } from '@/api/service-unit';

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

const props = defineProps({
  visible: Boolean,
  crmIds: Array,
  customType: String,
  dialogWidth: { type: Number, default: 640 },
  dialogTitle: { type: String, default: '划定服务单元' },
});

const formData = reactive({ serviceUnitId: null, crmIdList: [] });
const rules = {
  serviceUnitId: [
    {
      required: true,
      message: '未选择服务单元',
      type: 'error',
      trigger: 'change',
    },
  ],
};

const onOpened = () => {
  formData.serviceUnitId = null;
  formData.crmIdList = props.crmIds;
  formRef.value.clearValidate();
};

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

  const res = await serviceScopeBindBatchApi(formData).catch(() => {});
  if (!res) return;
  MessagePlugin.success('操作成功');
  emit('update:visible', false);
  emit('success');
};
</script>
