<template>
  <my-dialog
    :visible="visible"
    :header="title"
    :width="600"
    attach="body"
    :closeOnOverlayClick="false"
    @close="emit('update:visible', false)"
  >
    <t-form ref="formRef" :data="formData" :rules="rules" labelAlign="top">
      <t-row :gutter="[20, 20]">
        <t-col :span="6">
          <t-form-item label="考勤组名称" name="name">
            <t-input v-model="formData.name" clearable />
          </t-form-item>
        </t-col>

        <t-col :span="6">
          <t-form-item label="适用考勤对象" name="dingRoleIds">
            <select-role
              v-model="formData.dingRoleIds"
              :min-collapsed-num="10"
              :filterable="false"
              :disabled="isEdit"
              multiple
            >
            </select-role>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item
            v-if="!isEdit"
            label="适用供应商"
            name="supplierIdList"
            required-mark
          >
            <select-supplier
              v-model="formData.supplierIdList"
              multiple
              :min-collapsed-num="10"
              type="HUMAN"
            >
            </select-supplier>
          </t-form-item>
          <t-form-item
            v-else
            label="适用供应商"
            name="supplierId"
            required-mark
          >
            <select-supplier
              v-model="formData.supplierId"
              type="HUMAN"
              :disabled="isEdit"
            >
            </select-supplier>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="签到时段" name="signInOutTime">
            <t-time-range-picker
              v-model="formData.signInTime"
              format="HH:mm"
              class="width-full"
              clearable
              @change="signInTimeChange"
            />
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item name="signInOutTime">
            <template #label>
              <span>签退时段</span>
              <span class="color-warning m-l-5px"
                >(签到时段设置后，24小时未覆盖到的时段默认为签退时段)</span
              >
            </template>
            <t-time-range-picker
              v-model="formData.signOutTime"
              format="HH:mm"
              class="width-full"
              clearable
              @change="signOutTimeChange"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="审核角色" name="approveRoleIds">
            <select-role
              v-model="formData.approveRoleIds"
              :min-collapsed-num="10"
              :filterable="false"
              multiple
            >
            </select-role>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="是否开启人脸" name="faceOpen" required-mark>
            <select-enable
              v-model="formData.faceOpen"
              :options="TRUE_OR_FALSE_TYPE"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="允许补卡次数" name="reissueCardCount">
            <t-input-number
              v-model="formData.reissueCardCount"
              :decimalPlaces="0"
              :min="1"
              theme="column"
              style="width: 100%"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="服务单元" name="serviceId">
            <select-service-unit
              :disabled="isEdit"
              v-model="formData.serviceId"
              :filterParams="{ statusList: ['NEW', 'PUBLISH'] }"
            >
            </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="EditCheckinDialog">
import { ref, computed } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import useClearDialog from '@/hooks/useClearDialog';
import { checkinEditApi } from '@/api/system';
import { omit } from 'lodash';
import { TRUE_OR_FALSE_TYPE } from '@/config/constants';
const emit = defineEmits(['update:visible', 'success']);
const formRef = ref(null);

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

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

const { formData, isEdit } = useClearDialog(
  {
    id: null,
    name: '',
    serviceId: '',
    dingRoleIds: [],
    supplierId: '',
    signInTime: ['', ''],
    signOutTime: ['', ''],
    approveRoleIds: [],
    faceOpen: false,
    reissueCardCount: 2,
  },
  props,
  formRef,
  () => {
    for (let key in formData) {
      formData[key] = props.curRow[key];
    }
    formData.signInTime = props.curRow.signInTime.split('~');
    formData.signOutTime = props.curRow.signOutTime.split('~');
    formData.dingRoleIds = props.curRow.dingObjs
      .filter((item) => item.type === 'DING')
      .map((item) => item.roleId);
    formData.approveRoleIds = props.curRow.dingObjs
      .filter((item) => item.type === 'APPROVE')
      .map((item) => item.roleId);
  }
);
const rules = {
  name: [
    { required: true, message: '名称必填', type: 'error', trigger: 'change' },
    {
      min: 2,
      message: '至少需要2个字',
      type: 'error',
      trigger: 'change',
    },
    {
      max: 50,
      message: '至多需要50个字',
      type: 'error',
      trigger: 'change',
    },
  ],
  serviceId: [
    {
      required: true,
      message: '服务单元必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  dingRoleIds: [
    {
      required: true,
      message: '适用考勤对象必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  supplierId: [
    {
      required: true,
      message: '适用供应商必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  supplierIdList: [
    {
      validator: () => {
        if (!formData.supplierIdList || !formData.supplierIdList.length)
          return { result: false, message: '适用供应商必选' };

        return { result: true, type: 'success' };
      },
      type: 'error',
      trigger: 'change',
    },
  ],
  // signInTime: [
  //   {
  //     required: true,
  //     message: '签到时段必选',
  //     type: 'error',
  //     trigger: 'change',
  //   },
  // ],
  // signOutTime: [
  //   {
  //     required: true,
  //     message: '签退时段必选',
  //     type: 'error',
  //     trigger: 'change',
  //   },
  // ],
  signInOutTime: [
    {
      validator: () => {
        if (
          (formData.signInTime && !formData.signOutTime) ||
          (!formData.signInTime && formData.signOutTime)
        ) {
          return {
            result: false,
            message: '签到时段和签退时段必须同时填写',
          };
        }
        return {
          result: true,
          type: 'success',
        };
      },
      type: 'error',
      trigger: 'change',
    },
  ],
  approveRoleIds: [
    {
      required: true,
      message: '审核角色必选',
      type: 'error',
      trigger: 'change',
    },
  ],
  reissueCardCount: [
    {
      required: true,
      message: '允许补卡次数必填',
      type: 'error',
      trigger: 'change',
    },
  ],
};

const signInTimeChange = () => {
  formRef.value.validate({ fields: ['signInOutTime'] });
  formData.signOutTime = formData.signInTime
    ? [formData.signInTime[1], formData.signInTime[0]]
    : ['', ''];
};
const signOutTimeChange = () => {
  formRef.value.validate({ fields: ['signInOutTime'] });
};
const save = async () => {
  const valid = await formRef.value.validate();
  if (valid !== true) return;

  let data = {};
  for (let key in formData) {
    data[key] = formData[key];
  }
  const checkTime = (data) => data && !data.some((item) => !item);
  data.signInTime = checkTime(formData.signInTime)
    ? formData.signInTime.join('~')
    : '';
  data.signOutTime = checkTime(formData.signOutTime)
    ? formData.signOutTime.join('~')
    : '';
  data.dingObjs = [
    ...formData.dingRoleIds.map((item) => {
      return { roleId: item, type: 'DING' };
    }),
    ...formData.approveRoleIds.map((item) => {
      return { roleId: item, type: 'APPROVE' };
    }),
  ];
  data = omit(data, ['dingRoleIds', 'approveRoleIds']);

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

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