import {httpAction} from '../utils/manage'
import Sortable from 'sortablejs'
import {randomString} from "../utils/util";
import locleUtil from "./LocleUtil";

export const YchVxeTableMixin = {
  data() {
    return {
      title: this.$locale('m.common.label.operate'),
      visible: false,
      form: this.$form.createForm(this),
      spinning: 0,
      model: {},
      sortables: {},
      labelCol: {
        xs: {span: 24},
        sm: {span: 6}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      }
    }
  },
  methods: {
    $locale(params){
      return locleUtil.getLocale(params)
    },
    add() {
      if (typeof this.addBefore === 'function') {
        this.addBefore()
      }
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true

      if (typeof this.editAfter === 'function') {
        this.editAfter()
      }
    },
    copy (record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      if (typeof this.editAfter === 'function') {
        this.editAfter()
      }
      this.model.id = undefined
    },
    async handleOk() {
      if (this.spinning > 0 || !this.visible) {
        // 已经开启了遮罩或页面已经关闭
        return
      }
      this.spinning++
      // 触发表单验证
      this.form.validateFields(async (err, values) => {
        if (!err) {
          let httpUrl = '';
          let method = '';
          if (!this.model.id) {
            httpUrl += this.url.add;
            method = 'post';
          } else {
            httpUrl += this.url.edit;
            method = 'put';
          }

          let formData = Object.assign(this.model, values);
          if (typeof this.beforeSave === 'function') {
            formData = await this.beforeSave(formData)
            if (!formData) {
              this.spinning--
              return
            }
          }
          if (this.isGant){
            if (!formData.startDateField){
              this.$message.warning('请填写开始时间字段')
              return
            }
            if (!formData.endDateField){
              this.$message.warning('请填写结束时间字段')
              return
            }
            const obj = {
              isGantt: this.isGant,
              startDateField: formData.startDateField,
              endDateField: formData.endDateField
            }
            delete formData.startDateField
            delete formData.endDateField
            formData.ganttConfig = JSON.stringify(obj)
          }
          formData.treeLevel = isNaN(Number(formData.treeLevel)) ?  1 : Math.abs(Number(formData.treeLevel)) ? Math.abs(Number(formData.treeLevel)) : 1
          this.spinning++

          httpAction(httpUrl, formData, method).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.$emit('ok', formData)
              this.close()
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => {
            // 执行this.close()的时候，已经设置成了0
            if (this.spinning > 0) this.spinning--
          })
        } else {
          this.spinning--
        }
      })
    },
    async getTableDataSource($table, dataSource) {
      const errMap = await $table.fullValidate(true).catch(errMap => errMap)
      if (errMap) {
        const msgList = []
        Object.values(errMap).forEach(errList => {
          errList.forEach(params => {
            const {rowIndex, column, rules} = params
            rules.forEach(rule => {
              msgList.push(this.$locale('m.eform.formDesign.label.vxe_error', [rowIndex + 1, column.title, rule.message]))
            })
          })
        })
        const msg = msgList.map((msg, index) => index < 10 ? msg : (index === 10 ? '...' : ''))
        this.$message.warning(msg)

        // this.$message.warning({
        //   icon: () => {
        //     return null
        //   },
        //   content: (
        //     <div style="color: red; max-hclassName: 400px; overflow: auto;">
        //       {
        //         msgList.map((msg, index) => index < 10 ? <div>{msg}</div> : (index === 10 ? <div>{'...'}</div> : ''))
        //       }
        //     </div>
        //   )
        // })
        return false
      } else {
        return dataSource
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
      if (typeof this.afterClose === 'function') {
        this.afterClose()
      }
      this.spinning = 0
      this.model = {}
    },
    handleCancel() {
      this.close()
    },
    async insertRow(tableId, dataSource, initData, activeCell, index) {
      const $table = this.$refs[tableId]
      let id = randomString(32)
      const record = {
        id: id,
        ...initData
      }
      if (typeof index === "undefined" || index === -1) {
        dataSource.push(record)
      } else {
        dataSource.splice(index, 0, record)
      }
      if (activeCell) {
        await $table.setActiveCell(record, activeCell)
      }
    },
    deleteRow(tableId, dataSource, key) {
      const $table = this.$refs[tableId]
      const selectRecords = $table.getCheckboxRecords()
      if (selectRecords.length === 0) {
        this.$message.warning("没有选中数据")
        return
      }
      const idKey = key || 'id'

      const temp = {}
      dataSource.forEach((item, index) => {
        temp[item[idKey]] = index
      })
      let count = 0;
      selectRecords.forEach(item => {
        dataSource.splice(temp[item[idKey]] - count, 1)
        count++
      })
    },
    rowDrop(tableId, callback) {
      if (this.sortables[tableId]) {
        return
      }
      this.$nextTick(() => {
        const xTable = this.$refs[tableId]
        if (xTable){
          const sortableTool = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
            handle: '.drag-btn',
            onEnd: ({newIndex, oldIndex}) => {
              if (typeof callback === 'function') {
                callback.apply(this, [newIndex, oldIndex])
              }
            }
          })
          this.sortables[tableId] = sortableTool
        }
      })
    },
    afterRowDrop(newIndex, oldIndex, dataSource) {
      const currRow = dataSource.splice(oldIndex, 1)[0]
      dataSource.splice(newIndex, 0, currRow)
    },
    resetOrderNum(dataSource, orderNumId) {
      dataSource.forEach((item, index) => {
        item[orderNumId || 'orderNum'] = index + 1
      })
    },
  },
  beforeDestroy() {
    Object.keys(this.sortables).forEach(key => {
      this.sortables[key].destroy()
    })
    this.sortables = {}
  }
}
