<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="title"
      :async="true"
      width="800px"
      @confirm="handleSubmit"
      @close="handleClose"
      :clickModalClose="mode == 'show'"
      :button="mode != 'show'"
    >
      <el-form
        ref="formRef"
        :rules="rules"
        class="formdata"
        :model="formData"
        label-width="120px"
      >
        <el-form-item v-if="formData.id" label="任务ID" prop="id">
          <el-input
            :disabled="true"
            v-model="formData.id"
            clearable
            placeholder="请输入任务ID"
          />
        </el-form-item>
        <el-form-item label="任务日期" prop="datetime">
          <el-date-picker
            :disabled="isDisabled"
            v-model="formData.datetime"
            name="datetime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="changeDateTime"
          />
        </el-form-item>
        <el-form-item label="任务安排" prop="template_id">
          <el-input
            :disabled="isDisabled"
            v-model="formData.template_name"
            @click="isShow = true"
            name="template_id"
            clearable
            placeholder="请输入任务安排"
          />
        </el-form-item>
        <el-form-item label="任务描述" v-if="formData.template_name">
          <el-input
            disabled
            v-model="formData.templateInfo.content"
            placeholder="没有任务描述"
          />
        </el-form-item>
        <el-form-item label="一阶段天数">
          <el-input
            disabled
            v-model="formData.templateInfo.stage_day_one"
            clearable
            placeholder="请输入天数"
            type="number"
          >
            <template #append>天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="一阶段金额">
          <el-input
            disabled
            v-model="formData.templateInfo.money"
            clearable
            placeholder="请输入金额"
            type="number"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="二阶段天数">
          <el-input
            disabled
            v-model="formData.templateInfo.stage_day_two"
            clearable
            placeholder="请输入天数"
            type="number"
          >
            <template #append>天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="二阶段金额">
          <el-input
            disabled
            v-model="formData.templateInfo.money_two"
            clearable
            placeholder="请输入金额"
            type="number"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item
          v-if="noThreefilter(+formData.templateInfo.type)"
          label="三阶段天数"
        >
          <el-input
            disabled
            v-model="formData.templateInfo.stage_day_three"
            clearable
            placeholder="请输入天数"
            type="number"
          >
            <template #append>天</template>
          </el-input>
        </el-form-item>
        <el-form-item
          v-if="noThreefilter(+formData.templateInfo.type)"
          label="三阶段金额"
        >
          <el-input
            disabled
            v-model="formData.templateInfo.new_money_three"
            clearable
            placeholder="请输入金额"
            type="number"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="长期金额" v-if="+formData.templateInfo.types == 2">
          <el-input
            disabled
            v-model="formData.templateInfo.money_three"
            clearable
            placeholder="请输入金额"
            type="number"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="formData.templateInfo.type == 32" label="中转点">
          <el-input
            disabled
            placeholder="请选择中转点"
            :value="formData.templateInfo?.extend?.transfer?.address"
          />
        </el-form-item>
        <el-form-item v-if="formData.templateInfo.type == 32" label="终点">
          <el-input
            disabled
            placeholder="请选择终点"
            :value="formData.templateInfo?.extend?.terminus?.address"
          />
        </el-form-item>
        <!-- <el-form-item
          v-if="formData.templateInfo.type == 35"
          label="负责人"
          prop="task_admin"
          @click="clickTaskAdmin"
        >
          <el-input
            placeholder="请选择负责人"
            readonly
            v-model="formData.task_admin_name"
          />
        </el-form-item> -->
        <el-form-item
          v-if="formData.templateInfo.type == 35"
          label="充值金额(元)"
          prop="recharge"
        >
          <el-input
            disabled
            placeholder="请输入充值金额(元)"
            v-model="formData.templateInfo.recharge"
            type="number"
          />
        </el-form-item>
        <!-- <el-form-item v-if="mode == 'show'" label="">
          <el-button type="primary" @click="clickUpdate"> 修改 </el-button>
          <el-button type="danger" @click="clickDelete"> 删除 </el-button>
        </el-form-item> -->
      </el-form>
    </popup>
    <el-dialog v-model="isShow" title="选择任务安排" width="60%">
      <DialogIndex @customEvent="customEvent" :company_id="props.company_id" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="taskEidt">
import type { FormInstance, FormRules } from "element-plus";
import Popup from "@/components/popup/index.vue";
import { apiTaskAdd, apiTaskEdit, apiTaskDelete } from "@/api/task";
import { reactive, onUpdated, type PropType } from "vue";
import DialogIndex from "@/views/task_template/list_two.vue";
import { timeFormat } from "@/utils/util";
import feedback from "@/utils/feedback";
const route = useRoute();

const emit = defineEmits(["success", "close"]);
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");
const detailsdt = ref({});
const isShow = ref(false);
const title = ref("创建日程安排");

const changeDateTime = (e: any) => {
  formData.start_time = timeFormat(e[0]).split(" ")[0];
  formData.end_time = timeFormat(e[1]).split(" ")[0];
};

// 表单数据
const formData = reactive({
  id: "",
  create_user_id: "",
  status: "",
  template_id: "",
  scheduling_id: "",
  template_name: "",
  start_time: "",
  end_time: "",
  datetime: "",
  content: "",
  templateInfo: {},
});

interface RuleForm {
  datetime: Date | string;
  template_id: string;
}

const rules = reactive<FormRules<RuleForm>>({
  datetime: { required: true, message: "请选择时间范围", trigger: "blur" },
  template_id: {
    required: true,
    message: "请选择任务安排",
    trigger: "change",
  },
});

// 没有三阶段的任务类型ID, 使用以下方法过滤
const noThreeList = reactive([31, 32, 33, 34, 35, 45, 48, 49]);
const noThreefilter = (id: number) => {
  if (noThreeList.includes(id)) return false;
  else return true;
};

function customEvent(data: any) {
  isShow.value = false;
  formData.template_id = data.id;
  formData.template_name = data.title;
}

const formRef = ref(null);

const props = defineProps({
  task: {
    type: Object,
    defualt: () => {
      null;
    },
  },
  company_id: {
    type: String,
    default: "",
  },
});
const isDisabled = ref(false);

const updatedForm = async (task: any = null) => {
  try {
    formRef.value.clearValidate && formRef.value?.clearValidate();
  } catch (error) {
    console.log(error);
  }
  if (mode.value == "show") {
    title.value = "查看日程安排";
    isDisabled.value = true;
    Object.keys(formData).forEach((key: any) => {
      if (task[key] != null && task[key] != undefined)
        formData[key] = task[key];
    });
    formData.datetime = [
      formData.start_time.split(" ")[0],
      formData.end_time.split(" ")[0],
    ];
  } else {
    isDisabled.value = false;
    Object.keys(formData).forEach((key: any) => {
      formData[key] = "";
    });
  }
};

const clickUpdate = () => {
  mode.value = "edit";
  isDisabled.value = false;
};

// 删除
const clickDelete = () => {
  feedback.confirm("确定要删除吗?").then(async (e) => {
    if (e == "confirm") {
      await apiTaskDelete({ id: formData.id });
      popupRef.value?.close();
      emit("success");
    }
  });
};

// 提交按钮
const handleSubmit = () => {
  if (mode.value == "show") return popupRef.value?.close();
  else {
    formRef.value.validate(async (e: boolean) => {
      if (e) {
        const data = { ...formData };
        if (route.query.id) {
          data.scheduling_id = route.query.id.toString();
        }
        data.start_time = data.start_time.split(" ")[0];
        data.end_time = data.end_time.split(" ")[0];
        mode.value == "edit" ? await apiTaskEdit(data) : await apiTaskAdd(data);
        popupRef.value?.close();
        emit("success");
      }
    });
  }
};
//打开弹窗
const open = (type = "add") => {
  mode.value = type;
  popupRef.value?.open();
};

// 关闭回调
const handleClose = () => {
  emit("close");
};

defineExpose({
  open,
  updatedForm,
});
</script>
<style lang="scss" scoped>
.formdata {
  .el-form-item {
    .el-date-picker {
      width: 100%;
    }
  }
}
</style>
