<template>
  <h-modal
    id="EditExpData"
    :visible="compile"
    @ok="handleOk"
    closable
    centered
    @cancel="cancel"
    :title="title == t('ImpExp.common.Edit') ? t('ImpExp.common.Edit') : t('ImpExp.common.Added')"
    style="width: 886px"
    :destroyOnClose="true"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
  >
    <h-form
      :model="formState"
      ref="formRef"
      :layout="hFormGlobalConfig.layout"
      :labelCol="{ style: 'width:110px;' }"
      :rules="rules"
    >
      <h-row :gutter="30">
        <h-col :span="12">
          <h-form-item :label="t('ImpExp.common.Coding')" name="coding">
            <h-input
              v-if="props.title == t('ImpExp.common.Added')"
              allowClear
              v-model:value="formState.coding"
              :placeholder="t('ImpExp.common.Input')"
            ></h-input>
            <h-input
              v-if="props.title == t('ImpExp.common.Edit')"
              v-model:value="formState.coding"
              disabled
            ></h-input>
          </h-form-item>
        </h-col>
        <h-col :span="12">
          <h-form-item name="designation" :label="t('ImpExp.common.Designtion')">
            <h-input
              allowClear
              v-model:value="formState.designation"
              :placeholder="t('ImpExp.common.Input')"
            ></h-input>
          </h-form-item>
        </h-col>
        <h-col :span="12">
          <h-form-item
            name="format"
            :label="t('ImpExp.common.Format2')"
            :rules="[
              { required: true, message: t('ImpExp.common.FormatEmpty2'), trigger: 'change' },
            ]"
          >
            <h-select
              :placeholder="t('ImpExp.common.Choice')"
              v-model:value="formState.format"
              @change="handleChange"
              allowClear
            >
              <h-select-option value="EXCEL" label="EXCEL">EXCEL</h-select-option>
              <!--<h-select-option value="PDF" label="PDF">PDF</h-select-option>
              <h-select-option value="CUSTOM" :label="t('ImpExp.common.Custom')">
                {{ t('ImpExp.common.Custom') }}
              </h-select-option>-->
            </h-select>
          </h-form-item>
        </h-col>
        <h-col :span="12">
          <h-form-item
            name="way"
            :label="t('ImpExp.common.way')"
            :rules="[{ required: true, message: t('ImpExp.common.wayEmpty'), trigger: 'change' }]"
          >
            <h-select allowClear @change="handleChange" v-model:value="formState.way">
              <h-select-option :label="t('ImpExp.common.current')" value="CURRENT_PAGE">
                {{ t('ImpExp.common.current') }}
              </h-select-option>
              <h-select-option :label="t('ImpExp.common.currentSelect')" value="CURRENT_SELECT">
                {{ t('ImpExp.common.currentSelect') }}
              </h-select-option>
              <h-select-option :label="t('ImpExp.common.wholeData')" value="ALL_QUERY">
                {{ t('ImpExp.common.wholeData') }}
              </h-select-option>
            </h-select>
          </h-form-item>
        </h-col>
        <h-col :span="12">
          <h-form-item name="maxLine" :label="t('ImpExp.common.MaxLine2')">
            <h-input
              v-model:value="formState.maxLine"
              :placeholder="t('ImpExp.common.Input')"
            ></h-input>
          </h-form-item>
        </h-col>
        <h-col :span="12">
          <h-form-item name="state" label="是否启用">
            <h-radio-group style="display: flex; margin-top: 5px" v-model:value="formState.state">
              <h-radio :style="radioStyle" :value="'1'">{{ t('ImpExp.common.Enable') }}</h-radio>
              <h-radio :style="radioStyle" :value="'0'">
                {{ t('ImpExp.common.Deactivate') }}
              </h-radio>
            </h-radio-group>
          </h-form-item>
        </h-col>
        <h-col :span="12">
          <h-form-item
            name="identifying"
            :label="t('ImpExp.common.identifying2')"
            :rules="[
              { required: true, message: t('ImpExp.common.identifyingEmpty2'), trigger: 'change' },
            ]"
            style="margin-bottom: 0"
          >
            <h-upload-dragger
              v-model:fileList="fileList"
              name="file"
              :multiple="false"
              :customRequest="customRequest"
              @drop="handleDrop"
              :progress="progress"
              :maxCount="1"
              @remove="remove"
            >
              <template #itemRender="{ file, actions }"></template>
              <img src="../Picture/tubiao.svg" alt="" style="margin: 6px 0 20px" />
              <p class="ant-upload-text">{{ t('ImpExp.common.DropFile') }}</p>
              <p class="ant-upload-hint">{{ t('ImpExp.common.SupportExtend') }}</p>
            </h-upload-dragger>
            <div class="fileName" v-if="showName">
              <div class="linkName">
                <img src="../Picture/linkIcon.svg" alt="" class="link" />
                {{ diteFileName }}
              </div>
              <div class="demand">
                <img
                  src="../Picture/download.svg"
                  style="margin-right: 8px"
                  @click="downloadFile"
                  v-if="props.title == t('ImpExp.common.Edit')"
                />

                <img src="../Picture/deleteIcon.svg" alt="" class="del" @click="delFile" />
              </div>
            </div>
          </h-form-item>
        </h-col>
        <h-col :span="12">
          <h-form-item name="fileRule" :label="t('ImpExp.common.EditRule2')" class="col">
            <h-button @click="skip" style="margin-top: 5px; border-color: #4e5a70">
              {{ t('ImpExp.common.EditTemplate') }}
            </h-button>
            <x-m-l
              :compile="compile2"
              :fileRule="formState.fileRule"
              @closeModel="cancelModal"
              @textVal="gettextVal"
            ></x-m-l>
          </h-form-item>
        </h-col>
      </h-row>
    </h-form>
  </h-modal>
</template>
<script lang="ts">
import { ref, defineComponent, reactive, watch, computed } from 'vue';
import { editDataAPI, saveDataAPI } from '@/api/platform/ImpExp/Export';

import type { UploadProps } from 'ant-design-vue';
// 导入XML编辑器弹窗
import XML from './XML.vue';
import {
  downloadUrlAPI,
  FileUploadAPI,
  soleDataAPI,
  ExpDataAPI,
} from '@/api/platform/ImpExp/upload';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { message, HModal } from '@crami/ui';
import { useI18n } from '@crami/locale';
import type { RuleObject } from 'node_modules/ant-design-vue/lib/form';
import { hFormGlobalConfig } from '@/settings/config';
interface FormState {
  coding: string; //配置编码
  designation: string; //配置名称
  format: string; //导出格式
  way: string; //导出方式
  maxLine: string; //最大导出行数
  state: string; //是否启用
  fileRule: string; //导出文件映射规则
  identifying: string; //导出模板文件标识
}

export default defineComponent({
  name: 'EditExpData',
  components: { XML },
  props: ['compile', 'title', 'selectKey', 'search', 'val', 'NewObjectType'],
  setup(props, options) {
    const { t } = useI18n();
    const confirmLoading = ref<boolean>(false);
    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    const fileList = ref([]);
    // 点击时显示XML编辑器页面
    const compile2 = ref<boolean>(false);
    const skip = () => {
      compile2.value = true;
    };
    // 文件上传完毕后展示进度条
    const progress: UploadProps['progress'] = {
      strokeColor: {
        '0%': '#36a5f5',
        '100%': '#1890ff',
      },
      strokeWidth: 3,
      format: percent => `${parseFloat(percent.toFixed(2))}%`,
      class: 'test',
    };

    const visible = ref<boolean>(false);
    const formRef = ref();

    let timerID = null;
    let timerID2 = null;
    const rules = {
      maxLine: [
        { required: true, message: t('ImpExp.common.MaxLineEmpty'), trigger: 'change' },
        {
          trigger: 'change',
          validator: (_rule: RuleObject, value: number) => {
            return new Promise((resolve, reject) => {
              if (String(value).trim().length !== String(value).length) {
                return reject(t('ImpExp.common.forbid'));
              } else {
                if (!Number.isInteger(Number(value))) {
                  return reject(t('ImpExp.common.digits'));
                } else {
                  if (Number(value) <= 0) {
                    return reject(t('ImpExp.common.shouldNot'));
                  } else if (String(value).trim()) {
                    if (String(value).trim().length > 9) {
                      return reject(t('ImpExp.common.upperLimit'));
                    }
                  }
                }
              }
              return resolve(null);
            });
          },
        },
      ],
      coding: [
        { required: true, message: t('ImpExp.common.CodingEmpty'), trigger: 'change' },
        {
          trigger: 'change',
          validator: (_rule: RuleObject, value: string) => {
            return new Promise((resolve, reject) => {
              if (value.trim().length !== value.length) {
                return reject(t('ImpExp.common.forbid'));
              } else {
                if (value.length > 10) {
                  return reject(t('ImpExp.common.maxLine'));
                } else {
                  if (props.title == t('ImpExp.common.Added')) {
                    clearTimeout(timerID);
                    timerID = setTimeout(() => {
                      ExpDataAPI({
                        Data: {
                          ECODE: value,
                        },
                        NewObject: true,
                        connect: commonParams.value.connect,
                        lang: commonParams.value.lang,
                        objectID: '',
                        objectType: props.NewObjectType,
                        companyId: commonParams.value.companyId,
                      }).then(res => {
                        if (res.data.result == false) {
                          return reject(t('ImpExp.common.repetition'));
                        } else {
                          return resolve(null);
                        }
                      });
                    }, 300);
                  } else {
                    return resolve(null);
                  }
                }
              }
            });
          },
        },
      ],
      designation: [
        { required: true, message: t('ImpExp.common.DesigntionEmpty'), trigger: 'change' },
        {
          trigger: 'change',
          validator: (_rule: RuleObject, value: string) => {
            return new Promise((resolve, reject) => {
              if (value.trim().length !== value.length) {
                return reject(t('ImpExp.common.forbid'));
              } else {
                if (value.length > 10) {
                  return reject(t('ImpExp.common.maxLine'));
                } else {
                  if (value && ENAME_val.value != value) {
                    clearTimeout(timerID2);
                    if (props.title == t('ImpExp.common.Added')) {
                      timerID2 = setTimeout(() => {
                        soleDataAPI({
                          Data: {
                            ENAME: value,
                          },
                          NewObject: true,
                          connect: commonParams.value.connect,
                          lang: commonParams.value.lang,
                          objectID: '',
                          objectType: props.NewObjectType || 'P_SYS_EXPORT_RULE',
                          companyId: commonParams.value.companyId,
                        }).then(res => {
                          if (res.data.result == false) {
                            return reject(res.msg);
                          } else {
                            return resolve(null);
                          }
                        });
                      }, 300);
                    } else {
                      timerID2 = setTimeout(() => {
                        ImpDataAPI({
                          Data: {
                            ENAME: value,
                          },
                          NewObject: false,
                          connect: commonParams.value.connect,
                          lang: commonParams.value.lang,
                          objectID: '',
                          objectType: props.NewObjectType || 'P_SYS_EXPORT_RULE',
                          companyId: commonParams.value.companyId,
                        }).then(res => {
                          if (res.data.result == false) {
                            return reject(res.msg);
                          } else {
                            return resolve(null);
                          }
                        });
                      }, 300);
                    }
                  } else {
                    return resolve(null);
                  }
                }
              }
            });
          },
        },
      ],
      fileRule: [
        { required: true, message: t('ImpExp.common.EditRuleEmpty2'), trigger: 'change' },
        {
          trigger: 'change',
          validator: (_rule: RuleObject, value: string) => {
            return new Promise((resolve, reject) => {
              if (value.trim().length !== value.length) {
                return reject(t('ImpExp.common.forbid'));
              } else {
                return resolve(null);
              }
            });
          },
        },
      ],
    };

    const cancelModal = () => {
      compile2.value = false;
      formRef.value.validateFields('fileRule');
    };

    const handleOk = async () => {
      visible.value = true;
      await formRef.value.validateFields();
      confirmLoading.value = true;

      saveDataAPI({
        ObjectType: 'P_SYS_EXPORT_RULE',
        companyId: commonParams.value.companyId,
        connect: commonParams.value.connect,
        data: {
          ECODE: formState.coding,
          EID: props.title == t('ImpExp.common.Added') ? '' : props.selectKey,
          ENAME: formState.designation,
          EXPORTTYPE: formState.way,
          FILETYPE: formState.format,
          MAXCOUNT: formState.maxLine,
          SETTING: encodeURIComponent(formState.fileRule),
          STATE: formState.state,
          TEMPLATE: formState.identifying,
        },
        lang: commonParams.value.lang,
        mode: props.title == t('ImpExp.common.Added') ? 'add' : 'edit',
        modelName: 'P_SYS_EXPORT_RULE',
        newObject: props.title == t('ImpExp.common.Added') ? 'true' : 'false',
        objectID: '',
        productLine: commonParams.value.project,
        projectCode: commonParams.value?.projectCode,
        type: 'form',
        userId: commonParams.value.userId,
      }).then(res => {
        if (res.code == 200) {
          confirmLoading.value = false;
          message.success(res.msg);
          cancel();
          props.search([]);
        } else {
          message.warning(res.msg);
          confirmLoading.value = false;
          return;
        }
        localStorage.setItem('textVal', '');
      });
      dele.value = false;
    };
    const cancel = () => {
      // 使用options.emit将关闭方法传给父组件
      options.emit('closeModel', (visible.value = false));
      formState.coding = '';
      formState.designation = '';
      formState.format = 'EXCEL';
      formState.way = 'CURRENT_PAGE';
      formState.maxLine = '65535';
      formState.state = '1';
      formState.fileRule = '';
      formState.identifying = '';
      localStorage.setItem('textVal', '');
      fileList.value = [];
      showName.value = false;
    };
    // 按钮样式相关
    const radioStyle = reactive({
      display: 'flex',
      height: '30px',
      lineHeight: '30px',
    });

    const dele = ref<boolean>(true);

    // 文件上传
    const customRequest = async file => {
      let formData = new FormData();
      if (
        file.file.name.indexOf('xls') != -1 ||
        file.file.name.indexOf('xlsx') != -1 ||
        file.file.name.indexOf('csv') != -1 ||
        file.file.name.indexOf('xlsm') != -1
      ) {
        formData.append('file', file.file);
        formData.append('fileShowName', file.file.name);
        formData.append('filePath', 'platform');
        const res = await FileUploadAPI(formData);
        // console.log(res, fileList);
        if (res.code == 200) {
          showName.value = true;
          diteFileName.value = file.file.name;
          fileId.value = res.data?.eid ?? '';
          fileList.value[0].status = 'done';
          formState.identifying = res.data.eid;
          formRef.value.validateFields('identifying');
          message.success(t('ImpExp.common.FileUpload'));
        } else {
          message.warning(t('ImpExp.common.uploadFailing'));
          return;
        }
      } else {
        message.warning(t('ImpExp.common.SupportExtend'));
        return;
      }
    };

    const handleChange = (value: string) => {
      console.log(`selected ${value}`); //下拉框的值发生变化时触发
    };

    // 表单元素的值
    const formState = reactive<FormState>({
      coding: '',
      designation: '',
      format: 'EXCEL',
      way: 'CURRENT_PAGE',
      maxLine: '65535',
      state: '1',
      fileRule: '',
      identifying: '',
    });
    const gettextVal = data => {
      formState.fileRule = decodeURIComponent(data);
      // console.log(data);
    };

    const diteFileName = ref();
    const showName = ref<boolean>(false);

    const delFile = () => {
      return new Promise((resolve, reject) => {
        HModal.confirm({
          icon: false,
          title: t('ImpExp.common.delComfirm'),
          content: t('ImpExp.common.confirm3'),
          onOk() {
            showName.value = false;
            formState.identifying = '';
            resolve(true);
          },
          onCancel() {
            resolve(false);
          },
        });
      }).catch(() => {
        console.log('Oops errors!');
      });
    };

    const remove = () => {
      return new Promise((resolve, reject) => {
        HModal.confirm({
          icon: false,
          title: t('ImpExp.common.delComfirm'),
          content: t('ImpExp.common.confirm3'),
          onOk() {
            formState.identifying = '';
            resolve(true);
          },
          onCancel() {
            resolve(false);
          },
        });
      }).catch(() => {
        console.log('Oops errors!');
      });
    };
    const fileId = ref();
    const downloadFile = () => {
      HModal.confirm({
        icon: false,
        title: t('ImpExp.common.downloadConfirm'),
        content: t('ImpExp.common.downloadFile'),
        onOk() {
          return new Promise((resolve, reject) => {
            downloadUrlAPI(fileId.value)
              .then(res => {
                var xz = new XMLHttpRequest();
                console.log(xz);
                xz.open('GET', res.data.templateUrl, true);
                xz.responseType = 'blob';
                xz.onload = function (e) {
                  // console.log(e);
                  var url = window.URL.createObjectURL(xz.response);
                  var a = document.createElement('a');
                  a.href = url;
                  a.download = res.data.fileName;
                  a.click();
                };
                xz.send();
              })
              .catch();
            resolve(true);
          }).catch(() => console.log('Oops errors!'));
        },
      });
    };

    const ENAME_val = ref();
    watch(
      () => props.val,
      () => {
        formState.coding = props.val.ECODE;
        formState.designation = props.val.ENAME;
        formState.format = props.val.FILETYPE;
        formState.way = props.val.EXPORTTYPE;
        formState.maxLine = props.val.MAXCOUNT;
        formState.state = props.val.STATE;
        formState.fileRule = decodeURIComponent(props.val.SETTING);
        formState.identifying = props.val.TEMPLATE;
        localStorage.setItem('textVal', props.val.SETTING);
        fileId.value = props.val.TEMPLATE;
        ENAME_val.value = props.val.ENAME;
        if (props.title == t('ImpExp.common.Edit')) {
          editDataAPI({
            companyId: commonParams.value.companyId,
            connect: commonParams.value.connect,
            lang: commonParams.value.lang,
            objectID: props.val.TEMPLATE,
          }).then(res => {
            // console.log(res);
            if (res.code == 200) {
              showName.value = true;
              diteFileName.value = res.data.data.FILE_SHOW_NAME;
            }
          });
        } else if (props.title == t('ImpExp.common.Added')) {
          showName.value = false;
        }
      },
      { deep: true },
    );

    return {
      t,
      remove,
      downloadFile,
      delFile,
      rules,
      confirmLoading,
      diteFileName,
      showName,
      props,
      fileList,
      headers: {
        authorization: 'authorization-text',
      },
      cancelModal,
      skip,
      compile2,
      gettextVal,
      progress,

      handleDrop: (e: DragEvent) => {
        console.log(e);
      },
      customRequest,
      dele,

      visible,
      handleOk,
      cancel,

      formState,
      handleChange,

      radioStyle,
      formRef,
      hFormGlobalConfig,
    };
  },
});
</script>
<style lang="less" scoped>
.title_class {
  display: inline-flex;
  width: calc(100% - 100);
}
:deep(.ant-form-item-label) {
  display: block;
  width: 100%;
  // text-align: left;
}
.fileName {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  margin-top: 12px;
  cursor: pointer;
  .linkName {
    display: flex;
    align-items: center;
    .link {
      width: 25px;
      height: 12px;
    }
  }
  &:hover {
    .del {
      display: block;
    }
  }
  .demand {
    display: flex;
    justify-content: space-between;
    align-items: center;
    > img:nth-child(1) {
      width: 14px;
      height: 14px;
    }
  }
}
.del {
  width: 12px;
  height: 12px;
  color: #ccc;
  display: none;
  margin-right: 5px;
}
:deep(div.ant-upload-list-item.ant-upload-list-item-done.ant-upload-list-item-list-type-text) {
  margin-top: 12px;
}
</style>
