<template>
  <el-dialog v-model="modalVisible" width="800px" :show-close="false" :close-on-click-modal="false" top="10vh">
    <template #header="{ titleId, titleClass }">
      <div class="flex justify-between items-center border-b pb-3">
        <h4 :id="titleId" :class="titleClass">{{ editForm ? '编辑任务' : '新增任务' }}</h4>
        <div>
          <el-button v-if="!editForm" type="primary" :loading="['2'].includes(props.saveLoading)"
            @click="submitForm(formRef, true)">保存并新建</el-button>
          <el-button type="primary" :loading="['2'].includes(props.saveLoading)"
            @click="submitForm(formRef, false)">保存</el-button>
          <el-button @click="closeVisible()">取消</el-button>
        </div>
      </div>
    </template>
    <div class="h-[55vh] overflow-y-auto scroll-bar">
      <el-form ref="formRef" :model="form" label-width="100px" :rules="rules" class="flex flex-wrap form">
        <el-form-item label="任务名称" prop="taskName" required>
          <el-input v-model="form.taskName" type="textarea" placeholder="请输入任务名称" clearable maxlength="100"
            show-word-limit />
        </el-form-item>
        <el-form-item prop="priority" label="优先级" required>
          <el-select v-model="form.priority" placeholder="请选择" clearable>
            <el-option v-for="item in PRIORITY " :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item :label="form.taskType">
          <template #label>
            <el-select v-model="form.taskType" class="border resetSelect" style="width: 100px" @change="changeTaskType">
              <el-option v-for="item in TASK_TYPE" :key="item.value" :value="item.value" :label="item.label" />
            </el-select>
          </template>
          <template v-for="item in TASK_TYPE_FIELD">
            <el-select v-model="form[item.field]" v-if="form.taskType == item.type" placeholder="请选择" clearable
              filterable>
              <el-option v-for="item in taskTypeValueData" :key="item.value" :value="item.value" :label="item.label" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="联系人" v-if="TASK_TYPE.find(v => v.value === (form.taskType || '1'))?.show">
          <el-select v-model="form.contactsId" placeholder="请选择" clearable filterable>
            <el-option v-for="item in contactValueData" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行人">
          <el-select v-model="form.executorId" placeholder="请选择" clearable multiple filterable>
            <el-option v-for="item in executorValueData" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="重复提醒">
          <el-switch v-model="form.repeat" active-value="1" inactive-value="0" @change="changeRepeat" />
        </el-form-item>
        <template v-if="form.repeat === '1'">
          <el-form-item label="重复类型" label-width="7em">
            <el-select v-model="form.repeatType" placeholder="请选择" @change="changeRepeatType">
              <el-option v-for="item in REPEAT_TYPE" :key="item.value" :value="item.value" :label="item.label" />
            </el-select>
          </el-form-item>
          <template v-if="['0', '1', '2', '3'].includes(form.repeatType)">
            <el-form-item label="每" label-width="7em" v-if="form.repeatType == 3">
              <el-input-number v-model="form.repeatDesignSameday" controls-position="right" :min="1" />天
            </el-form-item>
            <el-form-item label="结束" label-width="7em">
              <el-radio-group v-model="form.endType" @change="changeEndType">
                <el-radio label="1" class="w-full">永不</el-radio>
                <el-radio label="2" class="w-full mb-3"><el-input-number v-model="form.repeatEndCount" :min="1"
                    controls-position="right" />
                  次以后
                </el-radio>
                <el-radio label="3" class="w-full">
                  <el-date-picker v-model="form.repeatEndDate" type="date" placeholder="选择日期" style="width:65%"
                    :disabled-date="(value: Date) => (new Date() > new Date(value))" />
                  以后
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
          <template v-if="['4'].includes(form.repeatType)">
            <el-form-item v-for="(v, i) in customeDate" class="flex justify-between items-center customeDate">
              <div>
                第{{ i + 1 }}次重复在
                <el-input-number :model-value="Number(v)" controls-position="right" @change="changeDate(i, $event)"
                  :min="1" />
                天后
              </div>
              <div>
                <el-icon size="24" @click="deleteCustomeDateItem(i)" class=" hover:text-blue-500 cursor-pointer">
                  <Delete />
                </el-icon>
              </div>
            </el-form-item>
            <el-form-item>
              <div>
                <el-icon size="24" @click="addCustomeDateItem()" class=" hover:text-blue-500 cursor-pointer">
                  <Plus />
                </el-icon>
              </div>
            </el-form-item>
          </template>
        </template>
        <el-form-item label="开始时间" label-width="7em" class="w50">
          <el-date-picker v-model="form.startDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="截止时间" label-width="7em" class="w50">
          <el-date-picker v-model="form.endDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <GenerateForm ref="generateFormRef" :data="generateFormData" :value="form" />
      <div v-if="editForm">
        <el-form-item label="操作记录" label-width="7em">
          <div class="w-full">
            <div v-for="item in form.taskLogs" class=" border-b-2 w-full pl-3">
              {{ `${item.operateTime} ${item.operateUser} ${item.operateDesc}` }}
            </div>
          </div>
        </el-form-item>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { PRIORITY, TASK_TYPE, TASK_TYPE_FIELD, defalutModalForm, REPEAT_TYPE, CUSTOMER_FORM_URL, defaultGenerateFormData } from "./api";
import { GenerateForm } from "@zmjs/form-design"
import { get } from '@/utils/request';
import { Delete, Plus } from "@element-plus/icons-vue"
import { FormInstance } from 'element-plus';
import { getFromValue } from '@/utils/tools';
import { Props, Emits, TASK_VALUE_TYPE, REPEAT_VALUE_TYPE, } from './type';
const props = defineProps<Props>()
const emits = defineEmits<Emits>();
watch(() => props.saveLoading, (val) => {
  if (val == "3") {
    formRef.value?.resetFields();
    form.value = { ...defalutModalForm };
  }
})
watch(() => props.visible, (val) => {
  formRef.value?.resetFields();
  modalVisible.value = val
  if (val) {
    get(CUSTOMER_FORM_URL).then(res => {
      if (Array.isArray(res.data) && res.data.length > 0) {
        generateFormData.value = JSON.parse(res.data[0].config)
      }
    })
  }
})
watch(() => props.editForm, (val) => {
  if (!val) {
    //TODO 如果是新增
    form.value = { ...defalutModalForm };
    taskTypeValueData.value = [{ label: '客户1', value: '1' }, { label: '客户2', value: '2' }];
    contactValueData.value = [{ label: '联系人1', value: '1' }, { label: '联系人2', value: '2' }];
    executorValueData.value = [{ label: '执行人1', value: '1' }, { label: '执行人2', value: '2' }];
    return
  }
  //TODO 如果是编辑
  form.value = { ...val };
  customeDate.value = (form.value.repeatDesignSameday || "").split(',').filter(Boolean);
  changeTaskType(form.value.taskType)
  contactValueData.value = [{ label: '联系人1', value: '1' }, { label: '联系人2', value: '2' }];
  executorValueData.value = [{ label: '执行人1', value: '1' }, { label: '执行人2', value: '2' }];

})
const rules = ref({
  taskName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
})
const form = ref<any>({});
const formRef = ref<FormInstance>();
const generateFormRef = ref<InstanceType<typeof GenerateForm>>();
const generateFormData = ref<any>(defaultGenerateFormData);
const modalVisible = ref(false);
function closeVisible() {
  generateFormData.value = defaultGenerateFormData;
  emits('close')
}
function submitForm(formEl: FormInstance | undefined, isClose: boolean) {
  if (!formEl) return
  formEl.validate((valid) => {
    if (!valid) {
      return false
    }
    const repeatDesignDay = customeDate.value.join(",")
    generateFormRef.value?.getData().then((res: any) => {
      let submitData = getFromValue({
        ...form.value,
        repeatDesignDay,
        ...res
      })
      emits('submit', submitData, isClose)
    }).catch((err: any) => {
      console.log(err);
    })
  })
}

const taskTypeValueData = ref<any>([])
function changeTaskType(value: TASK_VALUE_TYPE) {
  form.value = {
    ...form.value,
    taskType: value,
    customerId: null, //  客户id 0
    businessId: null, //商机id 1
    orderId: null, //  订单id 2
    clueId: null, //线索id 3
    contactsId: null, //联系人id
  }
  switch (value) {
    case "0":
      taskTypeValueData.value = [];
      setTimeout(() => {
        taskTypeValueData.value = [{ label: '客户1', value: '1' }, { label: '客户2', value: '2' }];
      }, 500)
      break;
    case '1':
      taskTypeValueData.value = [];
      setTimeout(() => {
        taskTypeValueData.value = [{ label: "商机1", value: "1" }, { label: "商机2", value: "2" }]
      }, 500)
      break;
    case '2':
      taskTypeValueData.value = [];
      setTimeout(() => {
        taskTypeValueData.value = [{ label: "订单1", value: "1" }, { label: "订单2", value: "2" }]
      }, 500)
      break;
    case '3':
      taskTypeValueData.value = [];
      setTimeout(() => {
        taskTypeValueData.value = [{ label: "线索1", value: "1" }, { label: "线索2", value: "2" }]
      }, 500)
      break;
    default:
      const _n: never = value;
      break;
  }
}

const contactValueData = ref<any>([])

const executorValueData = ref<any>([])

function changeRepeat(value: string | number | boolean) {
  form.value = {
    ...form.value,
    repeat: value,
    repeatType: "0", //重复类型
    endType: "1", //结束类型
    repeatEndNever: "1",
    repeatEndCount: null, //重复指定次数次数后结束
    repeatEndDate: null, //重复到指定日期后结束
    repeatDesignDay: null, //自定义日期
    repeatDesignSameday: null, //自定义周期
  }
  customeDate.value = [];
}

function changeRepeatType(value: REPEAT_VALUE_TYPE) {
  form.value = {
    ...form.value,
    repeatType: value, //重复类型
    endType: "1", //结束类型
    repeatEndNever: "1",
    repeatEndCount: null, //重复指定次数次数后结束
    repeatEndDate: null, //重复到指定日期后结束
    repeatDesignDay: null, //自定义日期
    repeatDesignSameday: null, //自定义周期
  }
  customeDate.value = [];
}

function changeEndType(value: string | number | boolean) {
  form.value = {
    ...form.value,
    endType: value, //重复类型
    repeatEndNever: value == "1" ? "1" : null,//永不结束
    repeatEndCount: null, //重复指定次数次数后结束
    repeatEndDate: null, //重复到指定日期后结束
    repeatDesignDay: null, //自定义日期
    repeatDesignSameday: null, //自定义周期
  }
}

const customeDate = ref<any>([])
function changeDate(index: number, value: number | undefined) {
  customeDate.value[index] = value;
}
function deleteCustomeDateItem(index: number) {
  customeDate.value = customeDate.value.filter((_item: number, i: number) => i !== index);
}
function addCustomeDateItem() {
  customeDate.value.push(undefined)
}


</script>

<style lang="scss">
.resetSelect {
  border: 0;

  .el-select__wrapper {
    box-shadow: none;
    padding-right: 0;
  }

  .el-select__selected-item {
    text-align: right;
  }
}

.customeDate {

  .el-form-item__content {
    justify-content: space-between;
  }
}

.el-form-item {
  width: 100%;
}

.form {
  .w50 {
    @apply w-1/2;
  }
}
</style>