<template>
  <el-card shadow="hover">
    <el-form ref="basicFormRef" v-loading="loading" :model="basicParams" :rules="rules" :inline="true" label-width="130px" label-position="left">
      <el-row>
        <el-form-item label="模版编码" prop="templateCode">
          <el-select v-model="basicParams.templateCode" placeholder="请输入模版编码" clearable @change="selectTemp">
            <template #header>
              <el-input v-model="likeName" placeholder="可根据模版名称模糊查询" @input="filterByTemplateName"></el-input>
            </template>
            <el-option
              v-for="dict in filteredList"
              :key="dict.templateCode"
              :label="dict.templateName + '-v' + dict.version"
              :value="dict.templateCode + '&' + dict.version"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="模版名称" prop="templateName">
          <el-input v-model="basicParams.templateName" placeholder="请输入模版名称" clearable />
        </el-form-item>
        <el-form-item label="归属系统" prop="systemOwner">
          <el-select v-model="basicParams.systemOwner" placeholder="请输入归属系统">
            <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属模块" prop="moduleOwner">
          <el-select v-model="basicParams.moduleOwner" placeholder="请输入归属模块">
            <el-option v-for="dict in print_module" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="打印归属" prop="printSystem">
          <el-select v-model="basicParams.printSystem" placeholder="请输入打印归属">
            <el-option
              v-for="dict in print_action_system"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              :disabled="dict.value === 'start'"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="输出类型" prop="outputType">
          <el-select v-model="basicParams.outputType" placeholder="请输入输出类型">
            <el-option v-for="dict in print_output_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="允许签章" prop="allowSeal">
          <el-select v-model="basicParams.allowSeal" @change="handleAllowSealSelect" placeholder="请输入是否允许签章">
            <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item v-if="basicParams.allowSeal === 'Y'" label="签章服务商" prop="signService">
          <el-select v-model="basicParams.signService" @change="handleSignServiceSelect" placeholder="请输入签章服务商">
            <el-option v-for="dict in serviceList" :key="dict.serviceId" :label="dict.serviceName" :value="dict.serviceId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="basicParams.allowSeal === 'Y'" label="签章类型" prop="signNum">
          <el-select v-model="basicParams.signNum" placeholder="请输入签章类型">
            <el-option v-for="dict in signTypeList" :key="dict.signNum" :label="dict.signDesc" :value="dict.signNum"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="是否多模版" prop="multiTemplate">
          <el-select v-model="basicParams.multiTemplate" placeholder="请输入是否多模版">
            <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="basicParams.multiTemplate === 'Y'" label="多模版处理方式" prop="multiTemplateHandling">
          <el-select v-model="basicParams.multiTemplateHandling" placeholder="请输入多模版处理方式">
            <el-option v-for="dict in print_multi_temp_handling" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本" prop="versionNumber">
          <el-input v-model="basicParams.versionNumber" disabled />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="增加原因" prop="description">
          <el-input v-model="basicParams.description" type="textarea" rows="4" placeholder="请输入增加原因" style="width: 300px" show-word-limit maxlength="1000" clearable />
        </el-form-item>
      </el-row>
    </el-form>
  </el-card>
</template>

<script setup name="TemplateBasic" lang="ts">
import { TemplateInfoForm } from '@/api/print/template/templateInfotypes';
import { RouteLocationNormalized } from 'vue-router';
import { addTemplateInfo, editTemplateInfo, queryTemplateList, quryTemplateInfo, selectTempByTempCode } from '@/api/print/template';
import { getServiceList, getSignList } from '@/api/print/typeConfig';

const router = useRouter();
const { proxy } = getCurrentInstance();

const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));
const { print_module } = toRefs<any>(proxy?.useDict('print_module'));
const { print_action_system } = toRefs<any>(proxy?.useDict('print_action_system'));
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));
const { print_output_type } = toRefs<any>(proxy?.useDict('print_output_type'));
const { print_multi_temp_handling } = toRefs<any>(proxy?.useDict('print_multi_temp_handling'));
const templateList = ref<any[]>([]);
const filteredList = ref<any[]>([]);

const showSearch = ref(true);
const basicFormRef = ref<ElFormInstance>();
const loading = ref(false);
const likeName = ref('');
const serviceList = ref([]);
const signTypeList = ref([]);
const signTypeStaticList = ref([]);

const data = reactive<SinglePageData<TemplateInfoForm>>({
  basicParams: {},
  rules: {
    templateName: [
      { required: true, message: '模版名称不能为空', trigger: 'blur' },
      { max: 50, message: '模版名称长度不能超过50个字', trigger: ['blur', 'change'] }
    ],
    description: [{ required: true, message: '增加原因不能为空', trigger: 'blur' }],
    systemOwner: [{ required: true, message: '归属系统不能为空', trigger: 'blur' }],
    moduleOwner: [{ required: true, message: '归属模块不能为空', trigger: 'blur' }],
    printSystem: [{ required: true, message: '打印归属不能为空', trigger: 'blur' }],
    outputType: [{ required: true, message: '输出类型不能为空', trigger: 'blur' }],
    allowSeal: [{ required: true, message: '是否允许签章不能为空', trigger: 'blur' }],
    multiTemplate: [{ required: true, message: '是否多模版不能为空', trigger: 'blur' }],
    multiTemplateHandling: [
      {
        validator: (rule, value, callback) => {
          if (basicParams.value.multiTemplate === 'Y' && !value) {
            callback(new Error('多模版处理方式不能为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur' // 无论 multiTemplate 的值是什么，这里都使用 'blur' 作为触发条件
      }
    ],
    signService: [
      {
        validator: (rule, value, callback) => {
          if (basicParams.value.allowSeal === 'Y' && !value) {
            callback(new Error('签章服务商不能为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    signNum: [
      {
        validator: (rule, value, callback) => {
          if (basicParams.value.allowSeal === 'Y' && !value) {
            callback(new Error('签章方式不能为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  }
});
const { basicParams, rules } = toRefs(data);

const getTemp = async (templateId: string | number) => {
  loading.value = true;
  basicParams.value.templateId = templateId;
  const res = await quryTemplateInfo(basicParams.value);
  Object.assign(basicParams.value, res.data);
  loading.value = false;
};

/** 新增修改按钮 */
// 子组件中的 handleAdd 和 handleEdit 方法
const handleAdd = (callback) => {
  basicFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        const res = await addTemplateInfo(basicParams.value);
        Object.assign(basicParams.value, res.data);
        proxy?.$modal.msgSuccess('操作成功');
        proxy?.$emit('processing-complete', { code: basicParams.value.templateId });
        callback();
      } catch (error) {
      } finally {
        loading.value = false;
      }
    }
  });
};

const handleEdit = (callback) => {
  basicFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        const res = await editTemplateInfo(basicParams.value);
        Object.assign(basicParams.value, res.data);
        proxy?.$modal.msgSuccess('操作成功');
        proxy?.$emit('processing-complete', { code: basicParams.value.templateId });
        callback();
      } catch (error) {

      } finally {
        loading.value = false;
      }
    }
  });
};

/** 返回按钮操作 */
const handleClose = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined,
    path: '/print/temp/printTempConstruct'
  };
  proxy?.$tab.closeOpenPage(obj);
};

//模糊查询
const filterByTemplateName = () => {
  if (likeName.value) {
    // 过滤操作
    filteredList.value = templateList.value.filter((item) => {
      return item.templateName.includes(likeName.value);
    });
  } else {
    // 如果 likeName 为空，显示原始列表
    filteredList.value = templateList.value;
  }
};
const quryTemplateList = async () => {
  const res = await queryTemplateList();
  templateList.value = res.data.tempList;
  filteredList.value = templateList.value;
};

onMounted(() => {
  const route = useRoute();
  const templateId = route.params.templateId as string | undefined;
  if (templateId) {
    getTemp(templateId);
  }
  quryTemplateList();
});

const selectTemp = async (newVal) => {
  const val = newVal.split('&');
  basicParams.value.templateCode = val[0];
  basicParams.value.versionNumber = val[1];
  const res = await selectTempByTempCode(basicParams.value);
  Object.assign(basicParams.value, res.data);
};

/**
 * 选择是否加签，如果是且没有服务列表，则获取服务列表
 * @param newVal
 */
const handleAllowSealSelect = async (newVal) => {
  if (newVal === 'Y' && serviceList.value.length === 0) {
    loading.value = true;
    const res = await getServiceList();
    serviceList.value = res.data;
    const resSign = await getSignList();
    signTypeStaticList.value = resSign.data;
    loading.value = false;
  }
};

/**
 * 选择服务商后，获取对应的加签类型列表
 * @param newVal
 */
const handleSignServiceSelect = async (newVal) => {
  signTypeList.value = signTypeStaticList.value.filter((item) => {
    return item.serviceId === newVal;
  });
};

/**
 * 对外暴露子组件方法
 */
defineExpose({
  handleAdd,
  handleClose,
  handleEdit
});
</script>

<style scoped lang="scss"></style>
