<script setup lang="ts">
import BusinessQuery from "/@/components/BasicForm/src/fields/business-permission/index.vue";
import {
  computed,
  onMounted,
  reactive,
  ref,
  shallowRef,
  watch,
  nextTick
} from "vue";
import { createHttpRequest } from "/@/views/time/_http";
import { ElForm, ElMessage } from "element-plus";

const emit = defineEmits(["refresh"]);

const httpDepart = createHttpRequest("account/depart");
const httpUser = createHttpRequest("admin/account/list");
const httpWechatTemplate = createHttpRequest("admin/WeTemplate/getTemplate");
const httpCreate = createHttpRequest("admin/DepartReport/create");
const httpUpdate = createHttpRequest("admin/DepartReport/edit");

const pushTypes = [{ value: "1", label: "每天" }];
const modalType = shallowRef("crate");

const options = [
  { value: "1", label: "部门报表" },
  { value: "2", label: "业务公司报表" }
];

const initialData = {
  report_type: "2",
  companyNo: "",
  report_name: "",
  template_name: "",
  template_id: "",
  template_param: "",
  push_type: "",
  depart_id: "",
  push_arr: []
};

const rules = {
  report_name: [
    { required: true, message: "请输入模板名称", trigger: "change" }
  ],
  template_id: [
    { required: true, message: "请选择微信模板", trigger: "change" }
  ],
  report_type: [
    { required: true, message: "请选择模板类型", trigger: "change" }
  ],
  push_type: [{ required: true, message: "请选择推送类型", trigger: "change" }],
  companyNo: [{ required: true, message: "请选择业务公司", trigger: "change" }],
  push_arr: [{ required: true, message: "请选择推送人", trigger: "change" }],
  depart_id: [{ required: true, message: "请选择部门", trigger: "change" }]
};

const title = computed(() =>
  modalType.value === "create" ? "创建模板" : "修改模板"
);
const businessQueryRef = ref<InstanceType<typeof BusinessQuery> | null>(null);
const wechatTemplate = ref<Record<string, string>[]>([]);
const cp_watchTemplate = ref<Record<string, string>[]>([]);
const departs = ref<Record<string, string>[]>([]);
const users = ref<Record<string, string>[]>([]);
const visible = ref(false);
const loading = ref(false);

const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const formData = ref({ ...initialData });

function handleTemplateChange(value) {
  const item = wechatTemplate.value.find(
    ({ template_id }) => template_id === value
  );
  formData.value.template_name = item!.title;
  formData.value.template_param = item!.content;
}

async function submit() {
  try {
    await formRef.value!.validate();
    const api = modalType.value === "update" ? httpUpdate : httpCreate;
    const result = await api(formData.value);
    if (result.code === 1) {
      emit("refresh");
      visible.value = false;
    } else {
      ElMessage.warning(result.message);
    }
  } catch (err) {
    console.log(err);
  }
}

onMounted(async () => {
  const wtResult = await httpWechatTemplate({});
  const dResult = await httpDepart({ size: 10000 });
  const uResult = await httpUser({
    is_wx: "1",
    size: 10000,
    depart_id: formData.value.depart_id
  });
  if (uResult.code === 1)
    users.value = uResult.data.list.filter(item => String(item.status) === "1");

  console.log(users.value);

  if (wtResult.code === 1) wechatTemplate.value = wtResult.data;
  if (dResult.code === 1)
    departs.value = [{ id: 0, name: "全部部门" }, ...dResult.data];
});

watch(
  () => [formData.value.report_type, wechatTemplate.value],
  val => {
    if (wechatTemplate.value.length === 0) {
      return;
    }

    if (formData.value.report_type === "1") {
      cp_watchTemplate.value = [
        wechatTemplate.value[0],
        wechatTemplate.value[1]
      ];
    } else {
      cp_watchTemplate.value = [wechatTemplate.value[2]];
    }
  },
  {
    immediate: true
  }
);

defineExpose({
  onDisplay: (data: any, _modalType: string) => {
    visible.value = true;

    modalType.value = _modalType;
    if (_modalType === "update") {
      formData.value = {
        ...data,
        ...(formData.value.report_type === "1"
          ? { companyNo: "" }
          : { depart_id: "0" })
      };
      formData.value.push_arr = data.pusher.map(({ user_id }) => user_id);

      console.log(data);
      if (data.companyNo) {
        nextTick(() => businessQueryRef.value.initialData(data.companyNo));
      }
      delete formData.value.pusher;
    } else {
      formData.value = { ...initialData };
    }
  }
});
</script>

<template>
  <el-dialog v-model="visible" :title="title" center>
    <el-form label-width="100px" :model="formData" :rules="rules" ref="formRef">
      <el-form-item label="模板名称:" prop="report_name">
        <el-input v-model="formData.report_name" placeholder="模板名称" />
      </el-form-item>

      <el-form-item label="模板类型:" prop="report_type">
        <el-select v-model="formData.report_type" style="width: 100%">
          <el-option
            v-for="opt in options"
            :key="opt.value"
            :value="opt.value"
            :label="opt.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="部门:"
        prop="depart_id"
        v-if="formData.report_type === '1'"
      >
        <el-select
          v-model="formData.depart_id"
          placeholder="部门"
          style="width: 100%"
          @change="handleChange"
        >
          <el-option
            v-for="depart in departs"
            :key="depart.id"
            :value="depart.id"
            :label="depart.name"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="业务公司:" prop="companyNo" v-else>
        {{ modalType.value }}
        <business-query
          ref="businessQueryRef"
          :not-initial="modalType !== 'create'"
          v-model="formData.companyNo"
        />
      </el-form-item>

      <el-form-item label="微信模板:" prop="template_id">
        <el-select
          style="width: 100%"
          v-model="formData.template_id"
          placeholder="微信模板"
          @change="handleTemplateChange"
        >
          <el-option
            v-for="template in cp_watchTemplate"
            :key="template.template_id"
            :value="template.template_id"
            :label="template.title"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="推送时间:"
        v-model="formData.push_type"
        prop="push_type"
      >
        <el-select
          style="width: 100%"
          placeholder="推送类型"
          v-model="formData.push_type"
        >
          <el-option
            v-for="type in pushTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="推送人:" v-model="formData.push_arr" prop="push_arr">
        <el-select
          style="width: 100%"
          placeholder="推送人"
          multiple
          filterable
          v-model="formData.push_arr"
        >
          <el-option
            filterable
            v-for="user in users"
            :key="user.id"
            :label="user.nickname"
            :value="user.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <div style="display: flex; justify-content: flex-end; width: 100%">
          <el-button type="primary" @click="submit" :loading="loading"
            >保存</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
