<script setup lang="ts">
import { FormRules, ElForm } from "element-plus";
import { reactive, ref } from "vue";
import { httpUpdate, httpAdd, httpDetail } from "/@/api/operate/setService";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/useNav";
import { Company, Card } from "/@/components/RemoteSelect";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
enum FROM_TYPE {
  create = "create",
  edit = "edit",
  view = "view"
}
const remoteCompanySelectRef = ref<InstanceType<typeof Company>>(null);
const remoteCardSelectRef = ref<InstanceType<typeof Card>>(null);
const { logout } = useNav();
const showModel = ref(false);
const TYPE = ref<FROM_TYPE>(FROM_TYPE.create);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const loading = ref(false);
const titleType = ref("");
const id = ref("");
const emit = defineEmits(["reload"]);
const initform = {
  company_id: "",
  card_id: "",
  id: "",
  title: "",
  original_price: 0,
  activity_price: 0,
  time: [],
  expiretime: "",
  content: "",
  remark: ""
};
const ruleForm = ref({ ...initform });
const rules = reactive<FormRules>({
  company_id: [{ required: true, trigger: "change", message: "请选择企业" }],
  card_id: [{ required: true, trigger: "change", message: "请选择企业" }],
  title: [{ required: true, trigger: "blur", message: "请输入服务名称" }],
  original_price: [
    { required: true, trigger: "change", message: "请选择原价" }
  ],
  activity_price: [
    { required: true, trigger: "change", message: "请选择活动价" }
  ],
  time: [
    {
      required: true,
      type: "array",
      trigger: "change",
      message: "请选择活动日期"
    }
  ],

  expiretime: [
    { required: true, trigger: "change", message: "请选择服务到期日期" }
  ],
  content: [{ required: true, trigger: "blur", message: "请输入服务介绍" }],
  remark: [{ required: true, trigger: "blur", message: "请输入备注" }]
});
const initData = async () => {
  const { code, data, message } = await httpDetail({ id: id.value });
  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      console.log(data);
      Object.keys(ruleForm.value).forEach(key => {
        if (key === "time") {
          const starttime = dayjs(data.starttime).format("YYYY-MM-DD");
          const endtime = dayjs(data.endtime).format("YYYY-MM-DD");
          ruleForm.value[key] =
            starttime !== "" && endtime !== "" ? [starttime, endtime] : [];
        } else if (key === "activity_price" || key === "original_price") {
          ruleForm.value[key] = Number(data[key]);
        } else {
          ruleForm.value[key] = data[key] ? data[key] + "" : "";
        }
      });
      const { company_title, card_title } = data;
      if (remoteCompanySelectRef.value) {
        (remoteCompanySelectRef.value as any).initalData({
          title: company_title
        });
      }
      if (remoteCardSelectRef.value) {
        (remoteCardSelectRef.value as any).initalData({
          title: card_title
        });
      }
    }
  });
};
async function show(node: any, did: string, isCreate: string) {
  id.value = did;
  loading.value = true;
  Object.keys(ruleForm.value).forEach(key => {
    ruleForm.value[key] = initform[key];
  });
  TYPE.value = isCreate;
  switch (TYPE.value) {
    case "create":
      titleType.value = "新建服务";
      break;
    case "edit":
      titleType.value = "编辑服务";
      break;
    case "view":
      titleType.value = "服务详情";
      break;
    default:
      titleType.value = "新建服务";
  }

  showModel.value = true;
  if (TYPE.value !== "create") {
    await initData();
  }
  loading.value = false;
}

function handleUpdate() {
  const data = {
    ...ruleForm.value
  };

  return {
    data,
    api: httpUpdate
  };
}

function handleCreate() {
  const data = {
    ...ruleForm.value
  };
  return {
    data,
    api: httpAdd
  };
}

function handleSave() {
  formRef.value.validate(async vaild => {
    if (vaild) {
      if (loading.value) return;
      loading.value = true;
      const { original_price, activity_price, time } = ruleForm.value;
      if (Number(original_price) < Number(activity_price)) {
        loading.value = false;
        ElMessage.warning("原价应该大于活动价！");
        return;
      }
      if (time.length !== 2) {
        loading.value = false;
        ElMessage.warning("活动时间不完整！");
        return;
      }

      const handler =
        TYPE.value === FROM_TYPE.create ? handleCreate : handleUpdate;

      const { api, data } = handler();
      let model = JSON.parse(JSON.stringify(data));
      model.starttime = dayjs(model.time[0]).format("YYYY-MM-DD");
      model.endtime = dayjs(model.time[1]).format("YYYY-MM-DD");
      model.expiretime = dayjs(model.expiretime).format("YYYY-MM-DD");
      delete model["time"];
      const { message, code } = await api(model);
      loading.value = false;
      responseHandle({
        code,
        message,
        logout,
        handler: () => {
          showModel.value = false;
          emit("reload");
        }
      });
    }
  });
}

defineExpose({
  show
});
</script>

<template>
  <el-dialog
    v-model="showModel"
    :close-on-press-escape="false"
    center
    append-to-body
    destroy-on-close
    :width="'1040px'"
    :title="titleType"
    v-loading="loading"
  >
    <el-form
      ref="formRef"
      :model="ruleForm"
      :rules="rules"
      label-width="85px"
      style="margin-top: -10px"
      class="demo-ruleForm"
      status-icon
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="企业名称" prop="company_id">
            <Company
              ref="remoteCompanySelectRef"
              v-model="ruleForm.company_id"
              :disabled="TYPE === 'view'"
              placeholder="企业名称"
            /> </el-form-item
        ></el-col>
        <el-col :span="6">
          <el-form-item label="卡类型" prop="card_id">
            <Card
              ref="remoteCardSelectRef"
              v-model="ruleForm.card_id"
              :disabled="TYPE === 'view'"
              placeholder="卡类型"
            /> </el-form-item
        ></el-col>
        <el-col :span="6">
          <el-form-item label="到期时间" prop="expiretime">
            <el-date-picker
              placeholder="到期时间"
              :disabled="TYPE === 'view'"
              type="date"
              v-model="ruleForm.expiretime"
              format="YYYY-MM-DD"
            /> </el-form-item
        ></el-col>
        <el-col :span="24">
          <el-form-item label="服务名称" prop="title">
            <ElInput
              placeholder="服务名称"
              :disabled="TYPE === 'view'"
              maxlength="50"
              v-model="ruleForm.title"
            /> </el-form-item
        ></el-col>

        <el-col :span="6">
          <el-form-item label="原价" prop="original_price">
            <el-input-number
              style="width: 100%"
              :disabled="TYPE === 'view'"
              :precision="2"
              :step="1"
              controls-position="right"
              v-model="ruleForm.original_price"
              :min="0"
              placeholder="原价"
              :max="99999999.99"
              clearable /></el-form-item
        ></el-col>
        <el-col :span="6">
          <el-form-item label="活动价" prop="activity_price">
            <el-input-number
              style="width: 100%"
              :disabled="TYPE === 'view'"
              :precision="2"
              :step="1"
              controls-position="right"
              v-model="ruleForm.activity_price"
              :min="0"
              placeholder="活动价"
              :max="99999999.99"
              clearable
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="活动时间" prop="time">
            <el-date-picker
              v-model="ruleForm.time"
              type="daterange"
              :disabled="TYPE === 'view'"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            /> </el-form-item
        ></el-col>

        <el-col :span="24">
          <el-form-item label="服务说明" prop="content">
            <ElInput
              placeholder="服务说明"
              :disabled="TYPE === 'view'"
              maxlength="500"
              type="textarea"
              v-model="ruleForm.content"
            /> </el-form-item
        ></el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <ElInput
              placeholder="备注"
              :disabled="TYPE === 'view'"
              maxlength="500"
              type="textarea"
              v-model="ruleForm.remark"
            /> </el-form-item
        ></el-col>
      </el-row>
      <div class="flex justify-end">
        <el-button
          v-if="TYPE !== 'view'"
          :loading="loading"
          :disabled="loading"
          type="primary"
          @click="handleSave"
          >保存</el-button
        >
        <el-button @click="showModel = false">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
