<script setup lang="ts">
import { FormRules, ElForm } from "element-plus";
import { reactive, ref } from "vue";
import { httpUpdate, httpDetail } from "/@/api/mobile/user";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/useNav";
import { Video } from "/@/components/RemoteSelect";
import dayjs from "dayjs";
enum FROM_TYPE {
  create = "create",
  edit = "edit",
  view = "view"
}
const { logout } = useNav();
const showModel = ref(false);
const Video_id = ref("");
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 = {
  id: "",
  username: "",
  company_title: "",
  card_title: "",
  name: "",
  mobile: "",
  time: [],
  video_ids: [],
  remark: ""
};
const ruleForm = ref({ ...initform });
const rules = reactive<FormRules>({
  username: [{ required: true, trigger: "bulr", message: "请输入账号" }],
  company_title: [{ required: true, trigger: "bulr", message: "请输入公司" }],
  card_title: [{ required: true, trigger: "bulr", message: "请输入卡类型" }],
  name: [{ required: false, trigger: "bulr", message: "请输入客户姓名" }],
  mobile: [{ required: false, trigger: "bulr", message: "请输入手机号" }],
  video_ids: [
    { required: true, type: "array", trigger: "change", message: "请选择视频" }
  ],
  time: [
    {
      required: true,
      type: "array",
      trigger: "change",
      message: "请选择有效日期"
    }
  ]
});

const initData = async () => {
  const { code, data, message } = await httpDetail({ id: id.value });
  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      Object.keys(ruleForm.value).forEach(key => {
        if (key === "time") {
          const starttime = data.starttime
            ? dayjs(data.starttime).format("YYYY-MM-DD")
            : "";
          const expiretime = data.expiretime
            ? dayjs(data.expiretime).format("YYYY-MM-DD")
            : "";
          ruleForm.value[key] =
            starttime && expiretime ? [starttime, expiretime] : [];
        } else if (key === "video_ids") {
          const { video_list } = data;
          ruleForm.value[key] = video_list.length > 0 ? video_list : [];
        } else {
          ruleForm.value[key] = data[key] ? data[key] + "" : "";
        }
      });
    }
  });
};
async function show(node: any, did: string, isCreate: string) {
  id.value = did;
  loading.value = true;
  Video_id.value = "";
  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 handleSave() {
  formRef.value.validate(async vaild => {
    if (vaild) {
      if (loading.value) return;
      loading.value = true;
      const handler = handleUpdate;

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

function videoChange(e) {
  if (e) {
    const { id, video_name } = e;
    const index = ruleForm.value.video_ids.findIndex(
      e => e.id + "" === id + ""
    );
    if (index == -1) {
      ruleForm.value.video_ids.push({ id, video_name });
    }
  }
}
defineExpose({
  show
});
</script>

<template>
  <el-dialog
    v-model="showModel"
    :close-on-press-escape="false"
    center
    append-to-body
    destroy-on-close
    :width="'650px'"
    :title="titleType"
    v-loading="loading"
  >
    <el-form
      ref="formRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      style="margin-top: -10px"
      class="demo-ruleForm"
      status-icon
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="账号" prop="username">
            <el-input
              v-model="ruleForm.username"
              :disabled="true"
              placeholder="账号"
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="卡类型" prop="card_title">
            <el-input
              v-model="ruleForm.card_title"
              :disabled="true"
              placeholder="卡类型"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="公司" prop="company_title">
            <el-input
              v-model="ruleForm.company_title"
              :disabled="true"
              placeholder="公司"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <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="12">
          <el-form-item label="客户姓名" prop="name">
            <el-input
              v-model="ruleForm.name"
              :disabled="TYPE === 'view'"
              placeholder="客户姓名"
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="ruleForm.mobile"
              maxlength="11"
              :disabled="TYPE === 'view'"
              placeholder="手机号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="ruleForm.remark"
              type="textarea"
              maxlength="500"
              :disabled="TYPE === 'view'"
              placeholder="备注"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="视频" prop="video_ids">
            <div v-show="ruleForm.video_ids && ruleForm.video_ids.length > 0">
              <el-tag
                v-for="(tag, index) in ruleForm.video_ids"
                :key="tag.id + index"
                class="mx-1"
                disable-transitions
                :closable="TYPE !== 'view'"
                size="large"
                @close="ruleForm.video_ids.splice(index, 1)"
              >
                {{ tag.video_name }}
              </el-tag>
            </div>
          </el-form-item></el-col
        >
        <el-col :span="16" v-if="TYPE !== 'view'">
          <el-form-item label="" prop="card_id">
            <Video
              v-model="Video_id"
              placeholder="请选择直播视频"
              :showDisabled="true"
              @change="videoChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="TYPE !== 'view' ? 8 : 24" 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>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
