<template>
  <h-modal
    id="EditImpData-queryModal"
    :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"
      :layout="hFormGlobalConfig.layout"
      :labelCol="{ style: 'width: 110px' }"
      ref="formRef"
      :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.Format')"
            :rules="[
              { required: true, message: t('ImpExp.common.FormatEmpty'), 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="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="checkOption"
            :label="t('ImpExp.common.CheckOption')"
            :rules="[
              { required: true, message: t('ImpExp.common.MechanismEmpty'), trigger: 'change' },
            ]"
          >
            <h-select
              :placeholder="t('ImpExp.common.Choice')"
              v-model:value="formState.checkOption"
              @change="checkChange"
              allowClear
            >
              <h-select-option value="0" :label="t('ImpExp.common.CheckDefault')">
                {{ t('ImpExp.common.CheckDefault') }}
              </h-select-option>
              <h-select-option value="1" :label="t('ImpExp.common.CheckCustom')">
                {{ t('ImpExp.common.CheckCustom') }}
              </h-select-option>
            </h-select>
          </h-form-item>
        </h-col>
        <template v-if="formState.checkOption === '0'">
          <h-col :span="12">
            <h-form-item
              name="mechanism"
              :label="t('ImpExp.common.Mechanism')"
              :rules="[
                { required: true, message: t('ImpExp.common.MechanismEmpty'), trigger: 'change' },
              ]"
            >
              <h-select
                :placeholder="t('ImpExp.common.Choice')"
                v-model:value="formState.mechanism"
                @change="handleChange"
                allowClear
              >
                <h-select-option value="1" :label="t('ImpExp.common.UserComfirm')">
                  {{ t('ImpExp.common.UserComfirm') }}
                </h-select-option>
                <h-select-option value="3" :label="t('ImpExp.common.Ignore')">
                  {{ t('ImpExp.common.Ignore') }}
                </h-select-option>
                <h-select-option value="2" :label="t('ImpExp.common.termination')">
                  {{ t('ImpExp.common.termination') }}
                </h-select-option>
              </h-select>
            </h-form-item>
          </h-col>
        </template>
        <template v-else>
          <h-col :span="12">
            <h-form-item
              :label="t('ImpExp.common.CheckPlugin')"
              name="checkPlugin"
              :rules="[
                { required: true, message: t('ImpExp.common.CheckPluginEmpty'), trigger: 'change' },
                {
                  pattern: /^[\s\S]{0,100}$/,
                  message: t('ImpExp.common.CheckPluginNum'),
                  trigger: 'change',
                },
              ]"
            >
              <h-input
                allowClear
                v-model:value="formState.checkPlugin"
                :placeholder="t('ImpExp.common.Input')"
              ></h-input>
            </h-form-item>
          </h-col>
          <h-col :span="12">
            <h-form-item
              :label="t('ImpExp.common.SavePlugin')"
              name="savePlugin"
              :rules="[
                { required: true, message: t('ImpExp.common.CheckPluginEmpty'), trigger: 'change' },
                {
                  pattern: /^[\s\S]{0,100}$/,
                  message: t('ImpExp.common.CheckPluginNum'),
                  trigger: 'change',
                },
              ]"
            >
              <h-input
                allowClear
                v-model:value="formState.savePlugin"
                :placeholder="t('ImpExp.common.Input')"
              ></h-input>
            </h-form-item>
          </h-col>
        </template>
        <h-col :span="12">
          <h-form-item name="maxLine" :label="t('ImpExp.common.MaxLine')">
            <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="identifying"
            :label="t('ImpExp.common.identifying')"
            :rules="[{ required: true, validator: validatorFile, trigger: 'change' }]"
            style="margin-bottom: 0"
          >
            <h-upload-dragger
              v-model:fileList="fileList"
              name="file"
              :multiple="false"
              :customRequest="customRequest"
              :before-upload="beforeUpload"
              @drop="handleDrop"
              :progress="progress"
              :maxCount="1"
              @remove="removeFile"
            >
              <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')"
                />
                <h-popconfirm
                  :title="t('ImpExp.common.confirm3')"
                  placement="topLeft"
                  @confirm="delFile"
                >
                  <img src="../Picture/deleteIcon.svg" alt="" class="del" />
                </h-popconfirm>
                <!-- <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="state" :label="t('ImpExp.common.whether')">
            <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="fileRule" :label="t('ImpExp.common.EditRule')" 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/Import';

import type { UploadProps } from 'ant-design-vue';
// 导入XML编辑器弹窗
import XML from './XML.vue';
import {
  downloadUrlAPI,
  FileUploadAPI,
  soleDataAPI,
  ImpDataAPI,
} 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/es/form';
import { hFormGlobalConfig } from '@/settings/config';
export default defineComponent({
  name: 'EditImpData',
  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 handleChange = (value: string) => {
      console.log(`selected ${value}`); //下拉框的值发生变化时触发
    };

    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(() => {
                      ImpDataAPI({
                        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(() => {
                        ImpDataAPI({
                          Data: {
                            ENAME: value,
                          },
                          NewObject: true,
                          connect: commonParams.value.connect,
                          lang: commonParams.value.lang,
                          objectID: '',
                          objectType: props.NewObjectType || 'P_SYS_IMPORT_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_IMPORT_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.EditRuleEmpty'), 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_IMPORT_RULE',
        companyId: commonParams.value.companyId,
        connect: commonParams.value.connect,
        data: {
          ECODE: formState.coding,
          EID: props.title == t('ImpExp.common.Added') ? '' : props.selectKey[0],
          ENAME: formState.designation,
          ERROPTION: formState.checkOption === '0' ? formState.mechanism : '',
          FILETYPE: formState.format,
          MAXCOUNT: formState.maxLine,
          SETTING: encodeURIComponent(formState.fileRule),
          STATEID: formState.state,
          TEMPLATE: formState.identifying,
          CHECKOPTION: formState.checkOption,
          CHECKPLUGIN: formState.checkOption === '0' ? '' : formState.checkPlugin,
          SAVEPLUGIN: formState.checkOption === '0' ? '' : formState.savePlugin,
        },
        lang: commonParams.value.lang,
        mode: props.title == t('ImpExp.common.Added') ? 'add' : 'edit',
        modelName: 'P_SYS_IMPORT_RULE',
        newObject: props.title == t('ImpExp.common.Added') ? 'true' : 'false',
        productLine: commonParams.value.project,
        projectCode: commonParams.value?.projectCode,
        objectID: '',
        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', '');
      });
    };
    const cancel = () => {
      // 使用options.emit将关闭方法传给父组件
      options.emit('closeModel', (visible.value = false));
      formState.coding = '';
      formState.designation = '';
      formState.format = 'EXCEL';
      formState.mechanism = '1';
      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 validatorFile = () => {
      if (formState.identifying.length == 0) {
        return Promise.reject(t('ImpExp.common.identifyingEmpty'));
      } else {
        const stringIndex = diteFileName.value.lastIndexOf('.');
        const fileType =
          stringIndex > -1
            ? diteFileName.value.substring(stringIndex + 1, diteFileName.value.length)
            : '';
        if (['xls', 'xlsx', 'csv', 'xlsm'].indexOf(fileType) < 0) {
          return Promise.reject(t('ImpExp.common.SupportExtend'));
        } else {
          return Promise.resolve(true);
        }
      }
    };
    const beforeUpload = file => {
      const isFileAccept =
        file.name.indexOf('xls') != -1 ||
        file.name.indexOf('xlsx') != -1 ||
        file.name.indexOf('csv') != -1 ||
        file.name.indexOf('xlsm') != -1;
      if (!isFileAccept) {
        message.error(t('ImpExp.common.UnsupportedFile'));
      }
      return isFileAccept;
    };
    // 文件上传
    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;
          fileList.value[0].status = 'done';
          diteFileName.value = file.file.name;
          fileId.value = res.data?.eid ?? '';
          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 formState = reactive({
      coding: '',
      designation: '',
      format: 'EXCEL',
      mechanism: '1',
      maxLine: '65535',
      state: '1',
      fileRule: '',
      identifying: '',
      checkOption: '0',
      checkPlugin: '',
      savePlugin: '',
    });
    const diteFileName = ref();
    const showName = ref<boolean>(false);

    const gettextVal = data => {
      formState.fileRule = decodeURIComponent(data);
      // console.log(data);
    };

    const delFile = () => {
      showName.value = false;
      formState.identifying = '';
    };

    //TODO:  删除已选择的文件
    const removeFile = () => {
      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.mechanism = props.val.ERROPTION;
        formState.maxLine = props.val.MAXCOUNT;
        formState.state = props.val.STATEID;
        formState.checkOption =
          props.val.CHECKOPTION !== '' && props.val.CHECKOPTION ? props.val.CHECKOPTION : '0';
        formState.fileRule = decodeURIComponent(props.val.SETTING);
        formState.identifying = props.val.TEMPLATE;
        formState.checkPlugin = props.val.CHECKPLUGIN;
        formState.savePlugin = props.val.SAVEPLUGIN;
        localStorage.setItem('textVal', props.val.SETTING);
        ENAME_val.value = props.val.ENAME;
        fileId.value = props.val.TEMPLATE;
        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 },
    );

    const checkChange = (event: any) => {
      console.log('checkChange', event);
      // if ()
    };

    return {
      t,
      downloadFile,
      delFile,
      removeFile,
      rules,
      confirmLoading,
      diteFileName,
      showName,
      fileList,
      props,
      skip,
      compile2,
      cancelModal,
      progress,
      visible,
      handleOk,
      cancel,

      formState,
      radioStyle,
      gettextVal,

      handleDrop: (e: DragEvent) => {
        console.log(e);
      },
      validatorFile,
      customRequest,
      beforeUpload,
      formRef,
      handleChange,
      checkChange,
      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>
