<template>
  <el-dialog v-model="props.visible" 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">{{ title || "新建任务" }}</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 mt-5">
      <el-form ref="formRef" :model="form" label-width="7em" :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 :disabled="disabledList && disabledList.includes('taskName')" />
        </el-form-item>
        <el-form-item prop="priority" label="优先级:" required>
          <el-select v-model="form.priority" placeholder="请选择" clearable
            :disabled="disabledList && disabledList.includes('priority')">
            <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"
              :disabled="disabledList && disabledList.includes('taskType')">
              <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 :disabled="disabledList && disabledList.includes(item.field)">
              <el-option v-for="v in taskTypeValueData" :key="v.id" :value="v[item.valueIndex]"
                :label="v[item.labelIndex]" />
            </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
            :disabled="disabledList && disabledList.includes('contactsId')">
            <el-option v-for="item in contactValueData" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行人:">
          <el-select v-model="form.executorId" placeholder="请选择" clearable multiple filterable
            :disabled="disabledList && disabledList.includes('executorId')">
            <el-option v-for="item in executorValueData" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="重复提醒:">
          <el-switch v-model="form.isRepeat" :active-value="1" :inactive-value="0" @change="changeRepeat" />
        </el-form-item>
        <template v-if="form.isRepeat === 1">
          <el-form-item label="重复类型:">
            <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="每:" v-if="form.repeatType == 3">
              <el-input-number v-model="form.repeatDesignSameday" controls-position="right" :min="1" />天
            </el-form-item>
            <el-form-item label="结束:">
              <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" :disabled="form.endType != 2" />
                  次以后
                </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))" value-format="YYYY-MM-DD"
                    :disabled="form.endType != 3" />
                  以后
                </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="开始时间:" class="w50">
          <el-date-picker v-model="form.startDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"
            :disabled="disabledList && disabledList.includes('startDate')" />
        </el-form-item>
        <el-form-item label="截止时间:" class="w50">
          <el-date-picker v-model="form.endDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"
            :disabled="disabledList && disabledList.includes('endDate')" />
        </el-form-item>
      </el-form>
      <GenerateForm ref="generateFormRef" :data="generateFormData" :value="form" />
      <div v-if="showLog">
        <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">
              {{ `${dayjs(item.modTime).format('YYYY-MM-DD HH:mm:ss')} ${item.userName} ${item.content}` }}
            </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, ALL_CUSTOM, ALL_CLUE, ALL_BUSINESS, ALL_CONTACTS, ALL_ORDERS, ALL_USERS, getTaskType } from "./api";
import { GenerateForm } from "@zmjs/form-design"
import { get, post } from '@/utils/request';
import { Delete, Plus } from "@element-plus/icons-vue"
import { FormInstance, dayjs } from 'element-plus';
import { getFromValue } from '@/utils/tools';
import { Props, Emits } from './type';
const props = defineProps<Props>()
const emits = defineEmits<Emits>();
watch(() => props.saveLoading, (val) => {
  if (val == "3") {
    formRef.value?.resetFields();
    form.value = { ...defalutModalForm };
    generateFormRef.value?.reset();
  }
})
watch(() => props.visible, (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)
      }
    })
  }
})
const customeData = ref<any>([])
const businessData = ref<any>([])
const orderData = ref<any>([])
const clueData = ref<any>([])
watch(() => props.editForm, (val) => {
  let taskType = 0;
  if (val) {
    taskType = getTaskType(val);
  }
  get(ALL_CUSTOM, {}).then(({ data }) => {
    customeData.value = data;//客户
    if (taskType == 0) {
      taskTypeValueData.value = data;
    }
  })
  get(ALL_BUSINESS, {}).then(({ data }) => {
    businessData.value = data;//商机
    if (taskType == 1) {
      taskTypeValueData.value = data;
    }
  })
  post(ALL_ORDERS, { pageIndex: -1, pageSize: -1 }).then(({ data }) => {
    orderData.value = data.record;//销售订单
    if (taskType == 2) {
      taskTypeValueData.value = data.record;
    }
  })
  get(ALL_CLUE, {}).then(({ data }) => {
    clueData.value = data;//线索
    if (taskType == 3) {
      taskTypeValueData.value = data;
    }
  })
  get(ALL_CONTACTS, {}).then(({ data }) => {
    contactValueData.value = data;//联系人
  })
  get(ALL_USERS, {}).then(({ data }) => {
    executorValueData.value = data;
  })
  if (val) {
    form.value = {
      ...val,
      taskType,
    }
  } else {
    form.value = { ...defalutModalForm }
  }
})
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 });
function closeVisible() {
  formRef.value?.resetFields();
  generateFormData.value = { ...defaultGenerateFormData };
  generateFormRef.value?.reset()
  emits('close')
}
function submitForm(formEl: FormInstance | undefined, isClose: boolean) {
  if (!formEl) return
  formEl.validate((valid: boolean) => {
    if (!valid) {
      return false as any
    }
    const repeatDesignDay = customeDate.value.join(",")
    generateFormRef.value?.getData().then((res: any) => {
      console.log(`{
        ...form.value,
        repeatDesignDay,
        ...res
      }`, {
        ...form.value,
        repeatDesignDay,
        ...res
      });
      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,
    customId: null, //  客户id 0
    businessOpportunityId: null, //商机id 1
    orderId: null, //  订单id 2
    clueId: null, //线索id 3
    contactsId: null, //联系人id
  }
  switch (value) {
    case 0:
      taskTypeValueData.value = [];
      setTimeout(() => {
        taskTypeValueData.value = customeData.value;
      }, 500)
      break;
    case 1:
      taskTypeValueData.value = [];
      setTimeout(() => {
        taskTypeValueData.value = businessData.value;
      }, 500)
      break;
    case 2:
      taskTypeValueData.value = [];
      setTimeout(() => {
        taskTypeValueData.value = orderData.value
      }, 500)
      break;
    case 3:
      taskTypeValueData.value = [];
      setTimeout(() => {
        taskTypeValueData.value = clueData.value;
      }, 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,
    isRepeat: 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 | undefined) {
  form.value = {
    ...form.value,
    endType: value, //重复类型
    repeatEndNever: value == 1 ? 1 : null,//永不结束
    repeatEndCount: null, //重复指定次数次数后结束
    repeatEndDate: null, //重复到指定日期后结束
    repeatDesignDay: 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>