<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2018-08-13 20:18:10
 * @LastEditTime: 2019-10-12 10:29:56
 * @LastEditors: Please set LastEditors
 -->
<template>
  <div class="config-data">
    <zte-table
      ref="table"
      :request-url="requestUrl + requestType"
      :export-url="exportAction"
      :export-title="exportTitle"
      :upload-url="importAction"
      :table-column="tableColumn"
      :download-url="downloadUrl"
      :download-data="downloadData"
      :button-list="buttonList"
      :params="params"
      v-bind="$attrs"
      v-on="$listeners"
      @add-row="handlerAdd"
      @delete-row="handlerDelete"
      @edit-row="handlerEdit"
      @row-check="handlerCheck"
      @switch-status="handlerSwitch">
      <template
        v-for="col of tableColumn"
        :slot="col.code"
        slot-scope="{ row, column, $index }">
        <slot
          v-if="col.temp"
          :name="col.code"
          :row="row"
          :column="column"
          :$index="$index">
        </slot>
      </template>
      <template
        v-if="$scopedSlots.content || $slots.content"
        slot="content" slot-scope="{ rows }">
        <slot name="content" :rows="rows" ></slot>
      </template>
    </zte-table>

    <el-dialog
      v-if="dialogVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="appendToBody"
      :title="dialogTitle"
      :width="dialogWidth"
      :append-to-body="appendToBody"
      :visible.sync="dialogVisible">
      <zte-form
        :labelWidth="labelWidth"
        :loading.sync="loading"
        :row-size="rowSize"
        :is-language="isLanguage"
        :item-info="itemInfo"
        :form="form"
        :rules="rules"
        :save-form="saveForm"
        cancel-text="关闭"
        @change="formValueChange"
        @submit="handlerSubmit"
        @picker-change="formPickerChange"
        @select-change="handlerFormSelectChange"
        @reset="dialogVisible = false">
        <template
          v-for="item of itemInfo"
          :slot="item.code"
          slot-scope="{ info, form }">
          <slot
            v-if="item.type === 'temp'"
            :name="'form-' + item.code"
            :info="info"
            :form="form"
          >
          </slot>
        </template>
      </zte-form>
    </el-dialog>
  </div>
</template>

<script>
import zteTable from './zte-table';
import zteForm from './zte-form';

export default {
  name: 'configData',
  components: { zteTable, zteForm },
  props: {
    requestUrl: {
      type: String,
      required: true,
    },
    buttonList: {
      type: Object,
      default: () => ({ add: true, del: true, edit: true, enable: true, disable: true }),
    },
    itemInfo: Array,
    title: String,
    isPagination: {
      type: Boolean,
      default: true,
    },
    appendToBody: {
      type: Boolean,
      default: false,
    },
    params: Object,
    addParams: Object,
    rules: {
      type: Object,
      default: () => ({}),
    },
    tableColumn: {
      type: Array,
      default: () => ([]),
    },
    rowSize: {
      type: Number,
      default: 2,
    },
    rowKey: {
      type: String,
      default: 'id',
    },
    tempName: {
      type: String,
      default: '模板.xls',
    },
    saveForm: {
      type: Boolean,
      default: false,
    },
    labelWidth: {
      type: Number,
      default: 120,
    },
    downloadUrl: {
      type: String,
      default: '/file/download',
    },
    dialogWidth:{
      type: String,
      default: '60%',
    },
    exportTitle:String,
  },
  data() {
    return {
      dialogTitle: this.title,
      dialogVisible: false,
      form: {},
      selectionRows: [],
      loading: false,
      // 下载导入模板路径
      downloadData: {},
    };
  },
  computed: {
    isLanguage() {
      if (this.itemInfo) {
        const isLanguage = this.itemInfo.some(item => item.lang);
        return isLanguage;
      }
      return false;
    },
    requestType() {
      const type = this.isPagination ? '/page' : '/list';
      return type;
    },
    importAction() {
      return `${this.requestUrl}/import`;
    },
    exportAction() {
      return this.exportTitle ? '' : `${this.requestUrl}/export`;
    }
  },
  methods: {
    getTableData() {
      this.$refs.table.getTableData();
      this.$emit('get-table-data');
    },
    handlerAdd() {
      this.form = {
        ...this.addParams,
      };
      this.itemInfo.forEach((item) => {
        if (item.value) {
          this.form[item.code] = item.value;
        }
        if (item.disabled === undefined || item.editable === false) {
          this.$set(item, 'disabled', false);
        }
        if (item.addable === false) {
          this.$set(item, 'show', false);
        }
      });
      this.$set(this, 'dialogTitle', this.title || this.$t('新增'));
      this.dialogVisible = true;
      this.$emit('add');
    },
    handlerCheck(selection) {
      this.selectionRows = selection;
      this.$emit('row-check', selection);
    },
    handlerEdit(row) {
      this.$set(this, 'dialogTitle', this.title || this.$t('编辑'));
      this.$emit('edit');
      this.itemInfo.forEach((item) => {
        if (item.editable === false) {
          this.$set(item, 'disabled', true);
        }
        if (item.addable === undefined || item.addable === false) {
          this.$set(item, 'show', true);
        }
      });
      this.$http.get(`${this.requestUrl}/${row[this.rowKey]}`).then(
        (res) => {
          res = res.data;
          this.form = res.data;
          this.dialogVisible = true;
        },
      ).catch();
    },
    handlerDelete(rows) {
      this.$emit('del');
      this.$http.delete(this.requestUrl, { data: rows.map(row => row[this.rowKey]) }).then(
        (res) => {
          res = res.data;
          if (res.code === 0) {
            this.$message.success(this.$t('删除成功'));
            this.getTableData();
          }
        },
      ).catch();
    },
    handlerSwitch(rows, type) {
      this.$emit('switch', type);
      this.$http.put(`${this.requestUrl}/${type}`, rows.map(row => row[this.rowKey])).then(
        () => {
          this.$message.success(this.$t('状态改变成功'));
          this.getTableData();
        },
      ).catch();
    },
    handlerSubmit(form) {
      const requestType = form[this.rowKey] ? 'put' : 'post';
      // 新增时需要添加额外参数
      // const params = this.addParams && !form[this.rowKey] ? Object.assign({}, form, this.params, this.addParams) : Object.assign({}, form, this.params);
      const params = Object.assign({}, form, this.params);
      this.$http[requestType](this.requestUrl, JSON.parse(JSON.stringify(params))).then(
        () => {
          this.loading = false;
          this.$message.success(this.$t('保存成功'));
          this.dialogVisible = false;
          this.getTableData();
        },
      ).catch(() => { this.loading = false; });
    },
    formValueChange(form) {
      this.$emit('form-value-change', form);
    },
    formPickerChange(form, item) {
      this.$emit('form-picker-change', form, item);
    },
    handlerFormSelectChange(val, info) {
      this.$emit('form-select-change', val, info)
    },
  },
  created() {
    if (this.buttonList.hasOwnProperty('downTemp')) {
      this.$http.post(`${this.requestUrl}/download`).then(
        (res) => {
          res = res.data;
          this.downloadData.filePath = res.url;
          this.downloadData.fileName = this.tempName;
        },
      ).catch();
    }
  }
};
</script>
