<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #areaId="{ model, field }">
        <a-tree-select
          show-search
          style="width: 100%"
          v-model:value="model[field]"
          :tree-data="treeData"
          :field-names="{ label: 'name', value: 'id' }"
          placeholder="请选择"
          allow-clear
          multiple
        />
      </template>
      <template #time="{ model, field }">
        <div>
          <div class="flex mt-1" v-for="(item, index) in timeslot" :key="index">
            <a-time-picker
              placeholder="开始时间"
              @change="(time, timeString) => beginTimeChange(time, timeString, index)"
              v-model:value="item.beginTime"
            />
            ~
            <a-time-picker
              placeholder="结束时间"
              @change="(time, timeString) => endTimeChange(time, timeString, index)"
              v-model:value="item.endTime"
            />
            <CloseCircleOutlined style="margin-left: 10px" @click="delTime(index)" />
          </div>
          <a-button type="primary" style="margin-top: 10px" @click="addTime">添加打开时间</a-button>
        </div>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './data';
  import { CloseCircleOutlined } from '@ant-design/icons-vue';
  import { addRole, updateRole, getDeptList } from '@/api/demo/system';
  import { useMessage } from '@/hooks/web/useMessage';
  import moment from 'moment';

  const { createMessage } = useMessage();
  const treeData: any = ref([]);
  const timeslot: any = ref([]);
  const timeList: any = ref([]);
  defineOptions({ name: 'DeptModal' });

  onMounted(() => {
    getTreeList();
  });
  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

  async function handleSubmit() {
    try {
      const values = await validate();
      let query = values;
      // 调用接口
      if (!unref(isUpdate)) {
        const data = await addRole(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          // TODO custom api
          closeModal();
          emit('success');
          return createMessage.success('新增成功');
        } else {
          return createMessage.error('新增失败');
        }
      } else {
        const data = await updateRole(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          // TODO custom api
          closeModal();
          emit('success');
          return createMessage.success('编辑成功');
        } else {
          return createMessage.error('编辑失败');
        }
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  const getTreeList = async () => {
    getDeptList().then((res) => {
      treeData.value = res;
    });
  };
  const delTime = (index) => {
    timeslot.value.splice(index, 1);
    timeList.value.splice(index, 1);
  };
  const addTime = () => {
    timeslot.value.push({
      beginTime: '',
      endTime: '',
    });
    timeList.value.push({
      beginTime: '',
      endTime: '',
    });
  };
  const beginTimeChange = (time, timeString, index) => {
    timeList.value[index].beginTime = timeString;
  };
  const endTimeChange = (time, timeString, index) => {
    timeList.value[index].endTime = timeString;
  };
</script>
