<template>
<div>
  <vxe-toolbar>
    <template #buttons>
      <a-button style="margin-right: 20px;" type="primary" key="file-excel" @click="handleExportTemplate" v-show="showButton">{{ LocleUtil.getLocale('m.eform.formDesign.label.xia-zai-dao-ru-mo-ban') }}</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="url.importFiveXlsUrl"
                @change="handleImportExcel"
                :customRequest="customRequest">
        <a-button v-show="showButton" type="default"  icon="import">{{ LocleUtil.getLocale('m.common.button.import') }}</a-button>
      </a-upload>
    </template>
  </vxe-toolbar>
  <vxe-table
    header-align="center"
    border
    :scroll-y="{enabled: false}"
    ref="xTable"
    class="sortable-row-vxe"
    show-header-overflow
    show-overflow
    resizable
    :tree-config="{transform: true,expandAll: true, reserve: true }"
    :span-method="mergeRowMethod"
    :row-style="getRowStyle"
    :row-config="{isHover: true, useKey: true, keyField: rowId, height: 60}"
    :edit-config="{trigger: 'click', mode: 'cell', activeMethod: activeRowMethod}"
    :data="dataSource">
    <vxe-column align="center" field="name" title="步骤" tree-node>
      <template #default="{ row, rowIndex }">
        {{ 'why' + (dataSource.findIndex(item => item.id == row.id) + 1)}}
      </template>
    </vxe-column>
    <vxe-column v-for="(item, index) in (formFlag? [recordConfig] : columnsVxe)" :key="item.key" :title="formFlag ? recordConfig.name :item.title"
                :edit-render="item.editRender" :min-width="item.minWidth"
                align="center"
                :formatter="item.formatter">
      <template #default="{ row, column }">
<!--        新增；编辑-->
        <vxe-textarea v-if="row[item.key]" :disabled="!showButton" v-model="row[item.key]" :transfer="true" rows="2"></vxe-textarea>

<!--        <vxe-input v-if="row[item.key]" :disabled="!showButton" v-model="row[item.key]" :transfer="true"></vxe-input>-->
<!--        详情-->
        <vxe-textarea v-else :disabled="!showButton" v-model="row[Object.keys(row).find(item => item !== 'children' && item !== 'id' && item !== 'parentId' && item !== '_X_ROW_CHILD')]" :transfer="true" rows="2"></vxe-textarea>

<!--        <vxe-input v-else :disabled="!showButton" v-model="row[Object.keys(row).find(item => item !== 'children' && item !== 'id' && item !== 'parentId' && item !== '_X_ROW_CHILD')]" :transfer="true"></vxe-input>-->
      </template>
      <template #edit="{ row, column }">
        <vxe-textarea :disabled="!showButton" v-model="row[item.key]" :transfer="true" rows="2" ></vxe-textarea>
<!--        <vxe-input :disabled="!showButton" v-model="row[item.key]" :transfer="true"></vxe-input>-->
      </template>
    </vxe-column>
    <vxe-column align="center" field="operate" title="操作">
      <template #default="{ row, rowIndex }">
        <a-button type="primary" @click="callFn(addButton)" v-show="showButton && rowIndex === 0">新增</a-button>
        <a-button style="margin-left: 10px;" @click="saveTable" v-show="showButton && rowIndex === 0">保存</a-button>
        <a-button type="error" v-show="showButton && rowIndex" @click="delSelectRows(dataSource.findIndex(item => item.id == row.id))">删除</a-button>
      </template>
    </vxe-column>
  </vxe-table>
</div>
</template>

<script>
import {handleCreateFunc, handleExecFunc} from "../utils/actions";
import {randomString} from "../utils/util";
import moment from "moment";
import YchConstant from "../utils/YchConstant";
import {importFiveWhyExcel} from "../utils/api/fivewhy";
import TokenStorageUtil from "../utils/TokenStorageUtil";
import LocleUtil from "../utils/LocleUtil";

export default {
  name: "KFiveWhy.vue",
  props: {
    itemRow: {
      default: () => {},
      type: Object
    },
    itemDetail: {
      default: () => {},
      type: Object
    },
    // 所有配置数据
    recordConfig: {
      type: Object,
      default: () => {
      }
    },
    // 列信息
    columns: {
      type: Array,
      required: true,
      default: () => []
    },
    // 是否显示操作按钮
    actionButton: {
      type: Boolean,
      default: false
    },
    // 增删按钮配置
    actionButtonConfig: {
      type: Array,
      default: () => []
    },
    // 是否禁用全部组件
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否可拖拽排序
    dragSort: {
      type: Boolean,
      default: false
    },
    // 排序关键字
    dragSortKey: {
      type: String,
      default: null
    },
    // 主键字段
    rowId: {
      type: String,
      default: "id"
    },
    // 表单对象
    form: {
      type: Object,
      default: () => {
      }
    },
    // 所有数据
    allDataSource: {
      type: Object,
      default: () => {
      }
    },
    fks: {
      type: Array,
      default: () => []
    },
    stores: {
      type: Object,
      default: () => {
        return {}
      }
    },
    formFlag: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      tokenHeader: { 'X-Access-Token': TokenStorageUtil.get(), 'content-type' : 'multipart/form-data' },
      sortable: null,
      findIndex: null,
      page: {
        multi: false,
        viewCode: null,
        rows: [],
        keys: [],
        labelField: null,
        fields: [],
      },
      dataSource: [],
      // 动态设置 this.disabled，导致重绘，有报错
      initDisabled: this.disabled,
      url: {
        importXlsUrl: YchConstant.PREFIX_EFORM + '/engine/viewEngine/importXls',
        exportTemplateUrl: YchConstant.PREFIX_EFORM + '/engine/viewEngine/exportTemplate',
        // 5WHY导入接口
        importFiveXlsUrl: YchConstant.PREFIX_SYSTEM + '/fiveWhy/importExcel'
      },
      viewName: '5WHY',
      isDisabledDetail: false,
      buttonDatas: {
        editableList: []
      }
    }
  },
  methods: {
    init(){
      this.isDisabledDetail = JSON.parse(sessionStorage.getItem('disabledDetail'));
      if (sessionStorage.getItem('buttonDatas')) {
        this.buttonDatas = JSON.parse(sessionStorage.getItem('buttonDatas'));
      }
      const value = this.recordConfig.options.defaultValue;
      if (this.itemRow) {
        //字表使用
        if (!this.itemDetail.key || !this.itemRow[this.itemDetail.key]) {
          this.insertRow();
          return;
        }
        this.dataSource = JSON.parse(this.itemRow[this.itemDetail.key]);
        this.findIndex = this.dataSource.length ? this.dataSource.length - 1 : null;
        return;
      }else{
        //表单使用
        if (this.$attrs.value) {
          this.dataSource = JSON.parse(this.$attrs.value);
          console.log(this.dataSource,'dataSource')
          return
        }
      }
      if (this.formFlag && value) {
        this.dataSource = JSON.parse(value);
        this.findIndex = this.dataSource.length ? this.dataSource.length - 1 : null;
      }else{
        this.insertRow();
      }
    },
    customRequest(file){
      console.log(file,'file')
      importFiveWhyExcel({'file': file.file}).then((res) => {
        this.dataSource = res.result;
        this.$nextTick(() => this.$refs.xTable.setAllTreeExpand(true));
      })
    },
    /* 导入 */
    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} 文件上传成功`);
          console.log(info)
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(this.LocleUtil.getLocale('m.common.tip.file_upload_error') + `: ${info.file.msg} `)
      }
    },
    //下载导入模板
    handleExportTemplate() {
      window.location.href="/5WHY导入模板.xlsx"
    },
    saveTable() {
      for (let i = 0; i < this.dataSource.length; i++) {
        this.dataSource[i].children && delete this.dataSource[i].children
        this.dataSource[i]._X_ROW_CHILD && delete this.dataSource[i]._X_ROW_CHILD
      }
      const key = this.itemDetail ? this.itemDetail.key : this.recordConfig.model;
      const row = this.itemRow || this.recordConfig;
      this.$emit('change',this.dataSource);
      this.itemDetail && this.$emit('setFieldValue',key,JSON.stringify(this.dataSource),row);
      this.$message.success('保存成功!');
    },
    validScript({cellValue, rule, rules, row, rowIndex, column, columnIndex}) {
      const validScript = this.columns.find(item => item.key === column.property).validScript
      const func = handleCreateFunc(validScript, this)
      const func_result = handleExecFunc(func, {cellValue, rule, rules, row, rowIndex, column, columnIndex})
      if (func_result && func_result !== true) {
        return new Error(func_result)
      }
    },
    async insertRow(formData) {
      const activeCell = null
      const $table = this.$refs.xTable
      const record = formData || this.getNewRow()
      // 新增前事件
      if (this.recordConfig.options && this.recordConfig.options.beforeAdded) {
        const func = handleCreateFunc(this.recordConfig.options.beforeAdded, this)
        const func_result = handleExecFunc(func, {$table, record})
        if (func_result === false) {
          return
        }
      }
      this.dataSource.push(record)
      const tempIndex = this.dataSource.findIndex(item => item.id === record.id);
      this.findIndex = tempIndex;
      this.$nextTick(() => $table && $table.setAllTreeExpand(true));

      // // TODO 暂时不支持新增后激活编辑的设置
      if (activeCell) {
        await $table.setActiveCell(record, activeCell)
      }
      // this.$emit("added", record, this.dataSource)
    },
    getNewRow() {
      const initData = {}
      console.log(this.columns,'this.columns')
      this.columns.forEach(item => {
        // initData[item.key] = item.defaultValue || null
        initData[item.key] = ''
      })
      let id = randomString(6)
      const record = {
        ...initData
      }
      if (this.formFlag || !this.columns.length) {
        record[this.recordConfig.key] = ''
      }
      record[this.rowId] = id
      record.parentId = typeof this.findIndex === 'number' ? this.dataSource[this.findIndex].id : null
      return record
    },
    //5why模式下删除row
    async delSelectRows(startIndex) {
      this.$confirm({
        title: '提示',
        content: '删除后，该层级下的所有内容将被删除，请确定',
        onOk: () => {
          const len = this.dataSource.length - 1
          this.$refs.xTable.remove([...this.dataSource.slice(startIndex, len)])
          this.dataSource.splice(startIndex,len)
          this.findIndex = startIndex - 1
        }
      })
    },
    valueChangeInput(e) {
      const that = this;
      // 延时执行，防止change事件拿到的row数据是旧的
      setTimeout(function () {
        that.$emit("valueChange", e)
      }, 1)
    },
    activeRowMethod({row, rowIndex, column, columnIndex}) {
      if (this.recordConfig.options && this.recordConfig.options.clickCell) {
        const func = handleCreateFunc(this.recordConfig.options.clickCell, this)
        const func_result = handleExecFunc(func, {row, rowIndex, column, columnIndex})
        if (func_result === false) {
          return false
        }
      }
      if (this.disabled) {
        this.$refs.xTable.clearActived()
        return false
      }
      return true;
    },
    formatterWithOptions({cellValue, row, column}) {
      const columnConfig = this.columnsVxe.find(item => item.key === column.property)
      const options = columnConfig.options || []
      const item = options.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    formatterWithDate({cellValue, row, column}) {
      return cellValue ? moment(cellValue, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD") : cellValue
    },
    formatterWithDatetime({cellValue, row, column}) {
      return cellValue
    },
    handleClickAdd() {
      const keyName = (this.columns && this.columns[0] && this.columns[0].key) || this.recordConfig.key;
      const flag = this.dataSource.every(item => item[keyName]);
      if (!flag) {
        this.$message.warning('请把内容填充完整再新增');
        return;
      }
      this.insertRow()
    },
    callFn(button, record, item) {
      if (!button && item && item.actionConfig) {
        button = JSON.parse(item.actionConfig)
      }
      if (button) {
        this[button.openType].apply(this, [button, record])
      }
    },
    handleDetail(button, record) {
      const formCode = button.formCode
      if (!formCode) {
        this.$message.warning(LocleUtil.getLocale('m.eform.formDesign.label.mei-you-pei-zhi-guan-lian-biao-dan'))
        return
      }
      let id = record.id;
      if (button.beforeScript) {
        const func = handleCreateFunc(button.beforeScript, this)
        const func_result = handleExecFunc(func, {button, record}, function () {
          this.handleDetailCallback(button, id, formCode, record)
        })
        if (!func_result) return;
      }
      this.handleDetailCallback(button, id, formCode, record)
    },
    handleDetailCallback(button, id, formCode, record) {
      this.$refs.form.detail(id, formCode, button.dialogSize, true, record)
      if (button.afterScript) {
        const func = handleCreateFunc(button.afterScript, this)
        handleExecFunc(func, {button, record})
      }
    },
    getRowStyle({row, rowIndex, $rowIndex}) {
      if (this.recordConfig.options && this.recordConfig.options.setRowStyle) {
        const func = handleCreateFunc(this.recordConfig.options.setRowStyle, this)
        const func_result = handleExecFunc(func, {row, rowIndex, $rowIndex})
        return func_result || {};
      }
      return {}
    },
    mergeRowMethod({row, _rowIndex, column, visibleData}) {
      if (this.recordConfig.options && this.recordConfig.options.spanMethod) {
        const func = handleCreateFunc(this.recordConfig.options.spanMethod, this)
        const func_result = handleExecFunc(func, {row, _rowIndex, column, visibleData})
        return func_result || {};
      }
      return {}
    }
  },
  computed: {
    LocleUtil() {
      return LocleUtil
    },
    //控制上传按钮显隐
    showButton(){
      // 脚本控制可编辑 优先级最高
      if (this.itemRow && this.itemRow.isShowEdit) {
        return true;
      }
      /*
      * 这一步用来判断是否从台账点开或者是否开启流程（disabledDetail为true）。
      * 然后判断是待办还是已办
      */
      if (this.isDisabledDetail || !this.buttonDatas || !this.buttonDatas.currentTaskInstanceVo) {
        // 在子表
        if (this.itemDetail) {
          return !this.itemDetail.disabled
        }else{
          //在表单
          return !this.recordConfig.options.disabled
        }
      }
      const currentTaskInstanceVo = this.buttonDatas.currentTaskInstanceVo;
      const identityString =  currentTaskInstanceVo && currentTaskInstanceVo.identityString;
      // 当已办的时候
      if (identityString && identityString.indexOf('已办') !== -1) {
        return false
      }
      // 当待办的时候，走过的节点统一禁用
      const currentFormCode = this.buttonDatas.formCode;
      const stepFormCode = sessionStorage.getItem('stepFormCode');
      if (stepFormCode == currentFormCode || !stepFormCode){
        return true
      }else{
        return false
      }
    },
    columnsVxe() {
      return this.columns.filter(item => item.type !== 'hidden').map(item => {
        const column = {...item}
        if (column.options) {
          column.options = column.options.map(vo => {
            return {
              value: vo.value,
              label: vo.label || vo.text
            }
          })
          column.options = [{
            value: '',
            label: ''
          }, ...column.options]
        }
        if (column.disabled || this.initDisabled) {
          // 动态设置 this.disabled，导致重绘，有报错
          // if (column.disabled || this.disabled) {
          // 列禁用
          if (column.type === "select") {
            column.formatter = this.formatterWithOptions
          }
        } else {
          if (column.type === "input") {
            column.editRender = {name: 'input', events: {change: this.valueChangeInput}}
          } else if (column.type === "inputNumber") {
            column.editRender = {name: 'input', attrs: {type: 'number'}, events: {change: this.valueChangeInput}}
          } else if (column.type === "select") {
            column.editRender = {name: 'select', options: column.options || [], events: {change: this.valueChangeInput}}
          } else if (column.type === "date") {
            column.editRender = {}
            column.slotEdit = "date";
          } else if (column.type === "datetime") {
            column.editRender = {}
            column.slotEdit = "datetime";
          } else if (column.type === "user") {
            column.editRender = {}
            column.slotEdit = "user";
          } else if (column.type === "dept") {
            column.editRender = {}
            column.slotEdit = "dept";
          } else if (column.type === "page") {
            column.editRender = {}
            column.slotEdit = "page";
          }else if (column.type === "fivewhy") {
            column.editRender = {name: 'input', events: {change: this.valueChangeInput}}
            column.slotEdit = "page";
          }
        }

        // TODO 图片控件目前缺少编辑功能
        if (column.type === "file") {
          column.slotDefault = "file";
        } else if (column.type === "user") {
          column.slotDefault = "user";
        } else if (column.type === "dept") {
          column.slotDefault = "dept";
        } else if (column.type === "page") {
          column.slotDefault = "page";
        } else if (column.type === "date") {
          column.formatter = this.formatterWithDate
        } else if (column.type === "datetime") {
          column.formatter = this.formatterWithDatetime
        } else if (column.type === "action") {
          column.slotDefault = "action";
        }else if (column.type === "fivewhy") {
          column.slotDefault = "fivewhy";
        }

        // 最小宽度
        if (column.width) {
          column.minWidth = column.width
        }

        return column
      })
    },
    addButton() {
      let result = null;
      if (this.actionButtonConfig && this.actionButtonConfig.length > 0) {
        result = this.actionButtonConfig.find(vo => vo.isDefault === 'Y')
      }
      if (!result) {
        result = {
          label: LocleUtil.getLocale('m.common.button.add'),
          openType: 'handleClickAdd',
          buttonIcon: 'plus',
          buttonStyle: 'primary',
        }
      }
      return result;
    },
    extButtons() {
      if (this.actionButtonConfig && this.actionButtonConfig.length > 0) {
        return this.actionButtonConfig.filter(vo => vo.isDefault !== 'Y')
      }
      return []
    },
  },
  created() {
    this.init();
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy()
      this.sortable = null
    }
  },
  watch: {
    // 动态设置 this.disabled，导致重绘，有报错
    // 允许从不可编辑变为可编辑，不允许从可编辑变为不可编辑
    disabled: {
      handler(value) {
        if (!value) {
          this.initDisabled = value
        }
      },
      immediate: false
    }
  }
}
</script>

<style scoped>

</style>
