import {deleteAction, getAction, downFile} from '../utils/manage'
import {filterObj} from '../utils/util';
import {initDictOptionMap} from '../packages/components/Common/dict/YchDictSelectUtil';
import TokenStorageUtil from "../utils/TokenStorageUtil";
import locleUtil from "./LocleUtil";
export const ViewMixin = {
  props: {
    objRelation: Object,//所有的关联关系
    pkFlg: Boolean,//触发点击的标识，用于事件监控
    parentTableName: String,//触发点击变化的表的标识，用于判断是否是自己的父表
    parentTableArr: Array,//所有含有子表的父表的集合，用于判断当前表是否为别人的子表
    initSelectedKeys: {
      type: Array,
      default: () => []
    },
    initSelectedRows: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      //token header
      tokenHeader: {'X-Access-Token': TokenStorageUtil.get()},
      rowKey: 'id',
      fks: [],//外键数据，查询时需要带着
      clickRecord: {},//当前点击行
      queryParam: {},//查询参数
      dataSource: [],//列表数据
      /*分页参数*/
      pagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '50', '100', '200', '500'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$locale('m.common.label.page_record_num', [total])
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      spinning: 0,//遮罩
      selectedRowKeys: [],
      selectionRows: [],
      toggleSearchStatus: false,//查询折叠状态
      myInstanceClassify: 'all',//流程状态
      canDel: false,
      originalColumns: [],//保存原始列信息，自定义列设置使用
    }
  },
  watch: {
    initSelectedKeys: {
      handler(value) {
        this.selectedRowKeys = value
      },
      immediate: true
    },
    initSelectedRows: {
      handler(value) {
        this.selectionRows = value
      },
      immediate: true
    },
    selectedRowKeys: {
      handler(value) {
        this.$emit("setSelectedRowKeys", value)
      }
    },
    selectionRows: {
      handler(value) {
        this.$emit("setSelectionRows", value)
      }
    }
  },
  created() {
    this.initOriginalColumns()
    this.initFkConfig();
    this.initDictConfig();
    if (this.fks.length == 0) {
      this.loadData(1);
    }
  },
  methods: {
    //保留原始列信息
    initOriginalColumns() {
      let dealColumns = [];
      this.columns.map(item => {
        let newObj = Object.assign({}, item);
        newObj['visible'] = item.visible !== false
        dealColumns.push(newObj);
      });
      //原始列信息
      this.originalColumns = dealColumns
      if (typeof this.customColumnChange === "function") {
        this.customColumnChange(this.originalColumns)
      }
    },
    initFkConfig() {
      if (this.objRelation && this.tableName) {
        const relation = this.objRelation[this.tableName];
        if (relation) {
          const fpk = relation.fks[0];
          this.fks = [{
            colCode: fpk.from,
            queryValue: null
          }];
        }
      }
    },
    initDictConfig() {
      if (this.dictConfig) {
        let dictCodes = Object.keys(this.dictConfig).join(",");
        if (dictCodes && dictCodes.length > 0) {
          initDictOptionMap(dictCodes).then((res) => {
            if (res.success) {
              Object.keys(this.dictConfig).forEach(key => {
                this.$set(this.dictConfig, key, res.result[key]);
              });
              //翻译列表显示值
              if (this.dataSource && this.dataSource.length > 0) {
                this.dataSource = [...this.dataSource];
              }
            }
          });
        }
      }
    },
    searchQuery() {
      this.loadData(1);
    },
    searchReset() {
      this.queryParam = {
        viewCode: this.viewCode
      };
      this.myInstanceClassify = 'all';
      this.loadData(1);
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      const aa = this.selectionRows.filter(item => selectedRowKeys.indexOf(item[this.rowKey]) !== -1);
      const bb = aa.map(row => row[this.rowKey]);
      const cc = selectionRows.filter(item => bb.indexOf(item[this.rowKey]) === -1);
      this.selectionRows = [...aa, ...cc];
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination;
      this.loadData();
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },
    //触发点击后，向其他列表传递事件和数据
    setPk(record) {
      this.clickRecord = record
      this.$emit('setPk', record, this.tableName)
      if (record[this.rowKey]) {
        this.onSelectChange(record[this.rowKey].split(','), [record])
      }
    },
    //判断当前列表是否为别人的子表
    isParentTable() {
      return this.parentTableArr && this.tableName && this.parentTableArr.indexOf(this.tableName) !== -1
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.pagination.current = 1;
      }
      const params = this.getQueryParams();//查询条件

      this.spinning++;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records;
          this.pagination.total = res.result.total;
          this.pagination.current = res.result.current

          //根据外键刷新
          this.refreshPk();
          this.canDel = this.myInstanceClassify == 'noRun' || this.myInstanceClassify == 'start';
        } else {
          this.$message.warning(res.message);
        }
      }).finally(() => {
        this.spinning--;
      });
    },
    getQueryParams() {
      let param = Object.assign({}, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.pagination.current;
      param.pageSize = this.pagination.pageSize;
      param.myInstanceClassify = this.myInstanceClassify;
      param = this.getFkParams(param);
      return filterObj(param);
    },
    getQueryField() {
      let str = "id,";
      this.columns.forEach(value => {
        str += "," + value.dataIndex;
      });
      this.fks.forEach(item => {
        str += "," + item.colCode;
      });
      return str;
    },
    //外键查询
    getFkParams(params) {
      this.fks.forEach(item => {
        //TODO 如果没有选择外键，如何过滤
        params[item.colCode] = item.queryValue || 'none'
      });
      return params;
    },
    clickThenCheck(record) {
      return {
        on: {
          click: () => {
            if (!this.isParentTable() || this.clickRecord[this.rowKey] === record[this.rowKey]) {
              return;
            }
            this.setPk(record)
          }
        }
      }
    },
    refreshPk() {
      if (!this.isParentTable()) {
        return
      }
      if (this.dataSource.length === 0 && !this.clickRecord[this.rowKey]) {
        return
      }
      let current
      if (this.clickRecord[this.rowKey]) {
        current = this.dataSource.find(vo => vo[this.rowKey] === this.clickRecord[this.rowKey])
      }
      if (!current) {
        this.setPk(this.dataSource.length > 0 ? this.dataSource[0] : {})
      } else {
        this.setPk(current)
      }
    },
    checkFks() {
      if (this.fks && this.fks.length > 0) {
        let flg = false;
        this.fks.forEach(vo => {
          if (!vo.queryValue) {
            flg = true;
          }
        });
        if (flg) {
          return false;
        }
      }
      return true;
    },
    watchPk() {
      if (this.objRelation && this.tableName && this.parentTableName) {
        const relation = this.objRelation[this.tableName];
        if (relation) {
          if (relation.parentTableName == this.parentTableName) {
            const fpk = relation.fks[0];
            const parentValue = relation.record[fpk.value];

            this.fks = [{
              colCode: fpk.from,
              queryValue: parentValue
            }];

            this.loadData(1);
          }
        }
      }
    },
    handleAddFlow() {
      if (!this.checkFks()) {
        this.$message.warning('请先选择主表记录');
        return;
      }
      this.$refs.flowForm.addFromBusiness(this.formCode, this.fks);
    },
    handleAdd() {
      if (!this.checkFks()) {
        this.$message.warning('请先选择主表记录');
        return;
      }
      this.$refs.form.add(this.fks);
    },
    $locale(params){
      return locleUtil.getLocale(params)
    },
    handleEdit(record) {
      if (!record) {
        if (this.selectedRowKeys.length !== 1) {
          this.$message.warning(this.$locale('m.common.tip.select_one_warn'));
          return;
        }
        record = this.selectionRows[0];
      }
      this.$refs.form.edit(record[this.rowKey]);
    },
    handleDetailFlow(record) {
      if (!record) {
        if (this.selectedRowKeys.length !== 1) {
          this.$message.warning(this.$locale('m.common.tip.select_one_warn'));
          return;
        }
        record = this.selectionRows[0];
      }
      this.$refs.flowForm.detailFromBusiness(record[this.rowKey], this.formCode);
    },
    handleDetail(record) {
      if (!record) {
        if (this.selectedRowKeys.length !== 1) {
          this.$message.warning(this.$locale('m.common.tip.select_one_warn'));
          return;
        }
        record = this.selectionRows[0];
      }
      this.$refs.form.detail(record[this.rowKey]);
    },
    handleBatchDel() {
      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning(this.$locale('m.common.tip.select_one_warn'));
        return;
      }
      let ids = this.selectedRowKeys.join(",");
      const that = this;
      this.$confirm({
        title: this.$locale('m.common.title.delete'),
        content: this.$locale('m.common.tip.delete_confirm2', [this.selectedRowKeys.length]),
        onOk: function () {
          that.spinning++;
          deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.loadData();
              that.onClearSelected();
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.spinning--;
          });
        }
      });
    },
    handleDel(record) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      if (!record) {
        this.$message.warning(this.$locale('m.common.tip.select_one_warn'));
        return;
      }
      const that = this
      this.$confirm({
        title: this.$locale('m.common.title.delete'),
        content: this.$locale('m.common.tip.delete_confirm'),
        onOk: function () {
          that.spinning++
          deleteAction(that.url.delete, {id: record[that.rowKey]}).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
              that.onClearSelected()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.spinning--
          })
        }
      })
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = {...this.queryParam}
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], {type: 'application/vnd.ms-excel'}), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    /* 导入 */
    handleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let {message, result: {msg, fileUrl, fileName}} = info.file.response
            let href = bootConfig[process.env.NODE_ENV].VUE_APP_API + fileUrl
            //   this.$warning({
            //       title: message,
            //       content: (
            //         < div >
            //         < span > { msg } < /span><br/ >
            //         < span > 具体详情请 < a href = { href } target = '_blank' download = { fileName } > 点击下载 < /a> </span >
            //     < /div>
            //   )
            // })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} ` + this.$locale('m.common.tip.file_upload_sucess'))
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(this.$locale('m.common.tip.file_upload_error') + `: ${info.file.msg} `)
      }
    },
    handleExt() {
      return;
    },
    // 新增/修改 成功时，重载列表
    modalFormOk() {
      this.loadData();
    },
  }
}
