<template>
  <div class="head-list">
    <avue-form
      ref="form"
      v-if="isSetConfigForm && readOnly"
      v-model="formObj"
      v-on="$listeners"
      :option.sync="finalOption"
    >
    </avue-form>
    <avue-form
      v-else-if="isSetConfigForm"
      ref="form"
      v-model="formObj"
      :option.sync="finalOption"
      v-on="$listeners"
    >
    </avue-form>
  </div>
</template>
<script>
import { ft, getBusinessAccount } from '../../../lib/utils.js';
import { checkDataType, checkFixDic, handlerSystemFiled, setRequired } from '../core/utils.js';
import { ElsTemplateConfigService } from '../../../lib/api/materials';
import { i18nConfig } from '../../../mixins/i18n';

const LABELS = {
  businessType: ft('i18n_common_business_type', '业务类型'),
  cancel: ft('i18n_common_cancel', '取消'),
  configuration: ft('i18n_common_configuration', '配置'),
  confirm: ft('i18n_common_confirm', '确定'),
  failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败')
};

export default {
  name: 'BusinessTypesProvider',
  mixins: [i18nConfig],
  props: {
    // elsAccountStation：远程获取 表格字段数据配置- 后续扩充 from 类型
    elsAccountStation: {
      type: String,
      default: ''
    },
    // businessModule: 远程获取 表格字段数据配置- 后续扩充 from 类型
    businessModule: {
      type: String,
      default: 'requisition'
    },
    // businessType： 远程获取 表格字段数据配置- 后续扩充 from 类型
    businessType: {
      type: String,
      default: ''
    },
    // businessTypeProperty: 用于匹配实际的业务类型数据属性
    businessTypeProperty: {
      type: String,
      default: function () {
        return '';
      }
    },
    // businessTypeValue: 业务类型数据, 用于 hideTable == true 时, 表单显示内容的刷新
    businessTypeValue: {
      type: String,
      default: ''
    },
    // businessTypeVersion: 业务类型版本
    businessTypeVersion: {
      type: String,
      default: ''
    },
    col: {
      type: Number,
      default: 0
    },
    data: {
      type: Object,
      default: function () {
        return {};
      }
    },

    // configOption: 外部提供数据来源, 通过 sessionStorage 加载数据 { name: string, timestamp: timestamp }
    configOption: {
      type: Object,
      default: function () {
        return null;
      }
    },
    option: {
      type: Object,
      default: function () {
        return { column: [] };
      }
    },
    originColumn: {
      type: Array,
      default: function () {
        return [];
      }
    },
    // needConfirm: 切换 businessType 需要确认
    needConfirm: {
      type: Boolean,
      default: false
    },

    // needConfirmTip: 切换 businessType 确认的提示信息
    needConfirmTip: {
      type: String,
      default: ''
    },
    // readOnly: 是否只读模式
    readOnly: {
      type: Boolean,
      default: false
    },
    // enAbleI18n: 是否支持多语言
    enAbleI18n: {
      type: Boolean,
      default: true
    },
    rowPermission: {
      type: Object,
      default: function () {
        return {};
      }
    }
  },
  data() {
    return {
      disabledProperties: {},
      isSetConfigForm: true,
      loadingConfig: false,
      isChanged: false,
      canceling: 0,

      finalOption: {
        menuBtn: false,
        submitBtn: false,
        clearBtn: false,
        column: [
          {
            label: LABELS.businessType,
            prop: 'businessType',
            type: 'select',
            span: 8
          }
        ]
      },
      formObj: {},

      configurations: {},

      selected: {},
      typeDicts: [],
      typeData: [],
      res: []
    };
  },
  watch: {
    'formObj.businessType'(newVal, oldVal) {
      if (newVal) {
        if (oldVal && this.needConfirm === true) {
          if (this.canceling === 0) {
            this.confirmChange(newVal, oldVal);
          } else {
            this.canceling = 0;
          }
        } else {
          this.loadConfigurationItem(newVal);
        }
      }
    },
    formObj(newVal) {
      if (!this.readOnly) {
        // 更新内容 同步更新到父对象
        this.$emit('update:data', newVal);
      }
    }
  },
  async created() {
    this.initOption();
    this.loadConfigurations();
  },
  methods: {
    checkForm(callback, failback) {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          callback && callback(done);
        } else {
          failback && failback();
          return false;
        }
      });
    },

    changeCancel(newVal, oldVal) {
      this.canceling = 1;
      this.formObj.businessType = oldVal;
    },

    changeOk(newVal) {
      this.$emit('confirmChanged', true);
      this.loadConfigurationItem(newVal);
    },

    confirmChange(newVal, oldVal) {
      const _this = this;

      this.$confirm({
        title: this.needConfirmTip,
        content: '',
        okText: LABELS.confirm,
        cancelText: LABELS.cancel,
        onOk() {
          _this.changeOk(newVal);
        },
        onCancel() {
          _this.changeCancel(newVal, oldVal);
        }
      });
    },

    doSelect(func, row, event, params = []) {
      this[func](row, event, params);
      this.$forceUpdate();
    },

    async filterColum(columns) {
      for (const item of columns) {
        const selected = this.selected;
        const itemProp = selected.fieldPermission[item.prop];

        await checkDataType(item);
        checkFixDic(item, this.fixSeleteDic);

        item.hide = true;
        item.display = false;

        if (itemProp) {
          if (itemProp.display && itemProp.display !== false) {
            if (this.enAbleI18n) {
              this.setI18n(item);
            } else {
              this.setDisplayName(item);
            }

            if (itemProp.isRequired === 'Y') {
              itemProp.isRequired = true;
            } else if (itemProp.isRequired === 'N') {
              itemProp.isRequired = false;
            }

            const isRequired = !!itemProp.isRequired;

            if (isRequired) {
              setRequired(item);
            }

            // 检查特定字段 固定处理
            if (itemProp.isDisabled || itemProp.isSystem === 'Y') {
              item.disabled = 'disabled';
              item.cell = false;
              item.rules = [];
            } else {
              item.cell = true;
            }

            if (item.isDisabled) {
              item.disabled = 'disabled';
            }

            if (item.isDisabled || itemProp.isDisabled || itemProp.isReadOnly === 'Y') {
              this.disabledProperties[item.prop] = 1;
            }
            if (item.isSystem === 'Y' || item.isReadOnly === 'Y') {
              handlerSystemFiled(item);
            }

            item.display = true;
            item.span = 6;
          }
        } else {
          if (item.isSystem === 'Y') {
            item.disabled = 'disabled';
            item.rule = [];
          }
        }
      }

      return columns;
    },

    getData() {
      const formData = JSON.parse(JSON.stringify(this.formObj));

      // 输出 templateName, templateVersion 供用户使用, 可能需要在接受后再处理为业务需要的值或抛弃(删除)
      if (formData.businessType) {
        const businessTypeData = this.typeData[formData.businessType];
        formData.businessTypeName = businessTypeData.templateName;
        formData.businessTypeVersion = businessTypeData.templateVersion;
      }

      // set real business type data and remove virtual business type data
      if (this.businessTypeProperty) {
        formData[this.businessTypeProperty] = formData.businessType;
      }

      delete formData.businessType;

      return formData;
    },

    getDisabledProperty(prop) {
      return this.disabledProperties[prop] || false;
    },

    go(item, row) {
      if (window.parent) {
        const router = {
          name: item.label,
          src: item.url + row[item.prop]
        };

        const event = {
          name: 'openNewTag',
          props: router
        };

        window.parent.postMessage(event, '*');
      } else {
        window.location.href = item.url;
      }
    },

    initOption() {
      if (this.readOnly) {
        this.finalOption.detail = true;
      } else {
        this.finalOption.detail = false;
      }
    },

    loadConfigurationItem(code) {
      const item = this.typeData[code];

      if (item) {
        ElsTemplateConfigService.detail(item)
          .then((res) => {
            if (res.data && res.data.code === '200' && res.data.data) {
              this.setConfigurationItem(res.data.data);
            } else {
              console.log('Failed to detail business type configuration.', res.data || res);
              this.$message.error(
                res.data.message ||
                  LABELS.failedToQueryData.replace(
                    '?',
                    `${LABELS.businessType.toLowerCase()} ${LABELS.configuration.toLowerCase()}`
                  )
              );
            }
          })
          .catch((err) => {
            console.log('Error to detail business type configuration.', err);
            this.$message.error(
              this.$message.error(
                LABELS.failedToQueryData.replace(
                  '?',
                  `${LABELS.businessType.toLowerCase()} ${LABELS.configuration.toLowerCase()}`
                )
              )
            );
          });
      }
    },

    loadConfigurations() {
      if (this.loadingConfig) {
        return;
      }

      this.loadingConfig = true;

      ElsTemplateConfigService.list({
        elsAccount: getBusinessAccount(),
        businessModule: this.businessModule,
        currentVersionFlag: 'Y'
      })
        .then((res) => {
          const TypeDicts = [];

          if (res.data && res.data.code === '200' && res.data.data) {
            const rows = res.data.data.rows || [];

            if (rows.length < 1) {
              return;
            }

            this.loadedConfigurations(rows);
          } else {
            this.typeDicts = TypeDicts;
            console.log('Failed to list business type configurations.', res.data);
            this.$message.error(
              res.data.message ||
                LABELS.failedToQueryData.replace(
                  '?',
                  `${LABELS.businessType.toLowerCase()} ${LABELS.configuration.toLowerCase()}`
                )
            );
          }
        })
        .catch((err) => {
          this.typeDicts = [];
          console.log('Error to list business type configurations.', err);
          this.$message.error(
            LABELS.failedToQueryData.replace(
              '?',
              `${LABELS.businessType.toLowerCase()} ${LABELS.configuration.toLowerCase()}`
            )
          );
        });
    },

    loadedConfigurations(rows) {
      const TypeDicts = [];

      const defaultNumber = this.businessTypeValue || rows[0].templateNumber;

      const TypeData = {};

      for (const item of rows) {
        TypeData[item.templateNumber] = {
          templateName: item.templateName,
          templateNumer: item.templateNumber,
          templateVersion: item.templateVersion,
          id: item.uuid
        };

        TypeDicts.push({
          value: item.templateNumber,
          label: item.templateName
        });
      }

      this.typeData = TypeData;
      this.typeDicts = TypeDicts;

      const form = this.$refs.form;

      if (form && form.updateDic) {
        form.updateDic('businessType', this.typeDicts);
      }

      this.formObj.businessType = defaultNumber;
    },

    setConfigurationItem(item) {
      const configJson = item.configJson || '{}';
      const json = JSON.parse(configJson);
      const fields = json.field || [];
      const fieldJson = json.fieldJson || {};
      const userStation = this.elsAccountStation || '';

      const table = json.table || [];
      const tableJson = json.tableJson || {};

      // 排除非法数据 $index
      for (const field of fields) {
        delete field.$index;
      }

      for (const tbl of table) {
        delete tbl.$index;
      }

      const fieldPermission = fieldJson[userStation] || {};
      const tablePermission = tableJson[userStation] || {};
      const saleTablePermission = tableJson.sale || {};

      // 由于与 businessType 重复, 如存在则删除 businessTypeProperty 对应的属性
      let fieldIndex = 0;

      for (const fieldItem of fields) {
        if (fieldItem.prop === this.businessTypeProperty) {
          fields.splice(fieldIndex, 1);
          break;
        }

        fieldIndex = fieldIndex + 1;
      }

      // this.configurations[item.templateNumber] = {
      //   name: item.templateName,
      //   fieldColumns: fields,
      //   fieldPermission: fieldPermission,
      //   tableColumns: table,
      //   tablePermission: tablePermission,
      //   rule: json.rule || {}
      // };

      if (!this.formObj.businessType) {
        this.formObj.businessType = item.templateNumber;
      }

      // 设置 templateName, templateVersion 供用户使用, 可能需要在接受后再处理为业务需要的值或抛弃(删除)
      if (this.formObj.businessType) {
        const businessTypeData = this.typeData[this.formObj.businessType];
        this.formObj.businessTypeName = businessTypeData.templateName;
        this.formObj.businessTypeVersion = businessTypeData.templateVersion;
      }

      // set real business type data and remove virtual business type data
      if (this.businessTypeProperty) {
        this.formObj[this.businessTypeProperty] = this.formObj.businessType;
      }

      this.$emit('businessTypeChange', {
        businessTypeCode: item.typeCode,
        businessType: item.templateNumber,
        templateVersion: item.templateVersion,
        configuration: {
          name: item.templateName,
          fieldColumns: fields,
          fieldPermission: fieldPermission,
          row: item,
          rule: json.rule || {},
          saleTablePermission: saleTablePermission,
          tableColumns: table,
          tablePermission: tablePermission,
          typeCode: item.typeCode
        }
      });
    }
  }
};
</script>
<style lang="scss">
@import './list.scss';
</style>
