<template>
  <a-modal
    width="80%"
    :cancel-text="labels.cancel"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :ok-text="labels.confirm"
    :title="labels.setCost"
    :visible.sync="fieldDialogVisible"
    @cancel="closeDialog"
    @ok="handleOk"
  >
    <el-select
      clearable
      filterable
      v-model="currentTemplate"
      :placeholder="labels.pleaseSelectCostTemplate"
      @change="handleTemplateChange"
    >
      <el-option
        v-for="item in templateList"
        :key="item.templateName"
        :label="item.templateName"
        :value="item.templateName"
      >
      </el-option>
    </el-select>
    <!-- :tabView="false" -->
    <fast2-config-tab-render
      :list="template"
      :providerData="data"
      :readOnly="true"
      :tabPermission="tabPermission"
    ></fast2-config-tab-render>
  </a-modal>
</template>

<script>
import { validateNull } from '../../../lib/validate';
import { getUserInfo } from '../../../lib/auth';
import { ft } from '../../../lib/utils.js';
import { costTemplateList, getConfig } from '../../../lib/api/index';

const LABELS = {
  cancel: ft('i18n_common_cancel', '取消'),
  confirm: ft('i18n_common_confirm', '确认'),
  costTemplate: ft('i18n_common_cost_template', '成本模板'),
  pleaseSelect: ft('i18n_common_please_select', '请选择'),
  setCost: ft('i18n_common_set_cost', '设置成本')
};

LABELS.pleaseSelectCostTemplate = `${LABELS.pleaseSelect}${LABELS.costTemplate.toLowerCase()}`;

// 采购方设置阶梯报价信息
export default {
  name: 'CostJsonDialog',
  components: {},
  created: function () {
    this.costTemplateList();
  },
  props: {
    fieldDialogType: String,
    fieldDialogVisible: {
      type: Boolean,
      default: false
    },
    field: Object
  },
  data() {
    return {
      labels: LABELS,
      confirmLoading: true,
      currentTemplate: '',
      templateList: [],
      template: [],
      tabPermission: [],
      form: {}
    };
  },
  watch: {
    field(newVal) {
      this.form = newVal;
      if (validateNull(this.form.$index)) {
        this.$nextTick(() => {
          if (this.$refs.formField) {
            this.$refs.formField.resetForm();
          } // 等弹窗里的form表单的dom渲染完在执行this.$refs.staffForm.resetFields()，去除验证
        });
      }
      if (newVal.costConstituteJson) {
        const costJson = JSON.parse(newVal.costConstituteJson);
        this.currentTemplate = costJson.templateName;
        this.tabPermission = costJson.permissionJson;
        this.template = this.tabPermission.template.column[0].data;
      }
      this.confirmLoading = false;
    }
  },
  methods: {
    closeDialog() {
      this.$emit('close-field-dialog');
    },

    costTemplateList() {
      const userInfo = getUserInfo();
      costTemplateList({
        elsAccount: userInfo.elsAccount,
        pageSize: 1000,
        businessModule: 'cost',
        currentVersionFlag: 'Y'
      }).then((res) => {
        this.templateList = res.data.data.rows;
      });
    },

    handleOk() {
      if (validateNull(this.currentTemplate)) {
        this.$message.error(LABELS.pleaseSelectCostTemplate);
        return;
      }
      const obj = {
        templateName: this.currentTemplate,
        templateJson: this.template,
        permissionJson: this.tabPermission
      };
      const costConstituteJson = JSON.stringify(obj);
      this.form.costConstituteJson = costConstituteJson;
      this.$emit('on-save-cost-json', this.form);
    },

    handleTemplateChange(value) {
      this.confirmLoading = true;
      const index = this.templateList.findIndex((item) => item.templateName === value);
      if (index === -1) {
        this.tabPermission = {};
        return;
      }

      const template = this.templateList[index];
      if (template && template.configJson) {
        this.tabPermission = JSON.parse(template.configJson);
      } else if (template) {
        getConfig(template.templateNumber, template.templateVersion).then((res) => {
          if (res.data.code === '200' && res.data.data && res.data.data.configJson) {
            this.tabPermission = JSON.parse(res.data.data.configJson);
            this.template = this.tabPermission.template.column[0].data;
            this.confirmLoading = false;
          }
        });
      }
    }
  }
};
</script>
