<template>
    <!--订单分配页面-->
    <dialog-edit :visible.sync="dialogVisible"
                 :title="$t('traceMgr.orderAllocation')"
                 :editModel="editModel"
                 :orderType="orderType"
                 :appendToBody="true" :autoClose="true" @close="dialogClose"
                 :footerBtnShow="false">
        <data-table :showSelection="true" v-bind="elHeightObj" @selectRowChange="selectionData" :columns="columns1" :api="getApi"
                    operateBtnLayout="" :queryParas="queryParas" :menuFlag="true" :loadPage="loadPage" :loadCount.sync="loadCount"
                     :stripe="true">
        </data-table>
        <el-row class="margin-top">
            <el-col :span="12" style="margin: 0px" >
                <el-tabs>
<!--                    <el-tab-pane :label="$t('traceMgr.listOfSuppliersToBeAssigned')" style="margin: 0px">-->
                        <span  class="typefaceSize">{{$t('traceMgr.listOfSuppliersToBeAssigned')}}</span>
                        <div   class="divider"></div>
                        <data-table v-bind="elHeightObj" :showSelection="true" :sourceData.sync="sourceData2" @selectRowChange="selectionData2" :columns="columns2"  :spanMethod="mergedCell" operateBtnLayout="" :queryParas="searchFormQueryParas"
                                      :stripe="false" :showPage="false">

                        </data-table>
<!--                    </el-tab-pane>-->
                </el-tabs>
            </el-col>
            <el-col :span="2">&nbsp;&nbsp;</el-col>
            <el-col :span="10">
                <el-tabs>
<!--                    <el-tab-pane :label="$t('traceMgr.listOfPersonnelToBeAssigned')">-->
                  <span  class="typefaceSize">{{$t('traceMgr.listOfPersonnelToBeAssigned')}}</span>
                  <div   class="divider"></div>
                        <data-table v-bind="elHeightObj" :showSelection="true" :sourceData.sync="sourceData3" @selectRowChange="selectionData3" :columns="columns3" operateBtnLayout="" :queryParas="searchFormQueryParas"
                                     :stripe="true" :showPage="false">

                        </data-table>
<!--                    </el-tab-pane>-->
                </el-tabs>
            </el-col>
        </el-row>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="medium" @click="distribution()">{{$t('traceMgr.distribution')}}</el-button>
            <el-button type="primary" size="medium" @click="save()">{{$t('common.save')}}</el-button>
            <el-button type="button" size="medium" style="background-color: #ffffff;" @click="closeDialogVisible()">{{$t('common.cancel')}}</el-button>
        </div>
    </dialog-edit>
</template>
<script>
import BaseEditPage from '@/pages/baseEditPage'
import { DialogEdit, DataTable } from 'newepoch-components'
import tracemgrApi from '@/api/tracemgrApi'
import mixin from '@/pages/mixin.js'

export default {
  mixins: [mixin],
  name: 'distributionOrderDialog',
  extends: new BaseEditPage(''),
  props: {
    editModel: {
      type: String
    },
    orderType: {
      type: String
    },
    handler: {
      type: Function
    },
    form: {
      type: Array
    }
  },
  components: {
    DialogEdit,
    DataTable,
    tracemgrApi
  },
  computed: {
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (value) {
        this.$emit('update:visible', value)
      }
    },
    getApi: {
      get: function () {
        return tracemgrApi['distributionOrderDialog']
      }
    }
  },
  data: function () {
    return {
      loadCount: 0,
      loadPage: 'getAllocateDataByFactoringCommissioner',
      type: '',
      mode: '0',
      sourceData1: [],
      sourceData2: [],
      sourceData3: [],
      chooseData2: [],
      chooseData3: [],
      isChoose: false,
      spanArr: [],
      queryParas: {
        pageIndex: 1,
        pageSize: 10,
        orderType: this.orderType
      },
      sIdx: 0,
      position: 0,
      sameRowArr: [],
      // api: {},
      tableApi: {},
      previewQueryParas: {
        pageIndex: 1,
        pageSize: 10,
        orderType: this.orderType
      },
      searchFormQueryParas: {
        productType: '',
        productId: ''
      },
      columns1: [
        // 保理专员
        {
          prop: 'factoringUserName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.factoringCommissioner
          // width: '200px'
        },
        // 本期目标订单数
        {
          prop: 'targetOrders',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.currentTargetOrders
          // width: '200px'
        },
        // 本期分配订单数（未完成/总数）
        {
          prop: 'assignedOrders',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.numberOfOrdersAllocatedInTheCurrentPeriod1,
          width: '140px'
        },
        // 本月订单数（未完成/总数）
        {
          prop: 'monthNum',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.noFinishOrdersOfThisMonth,
          width: '120px'
        },
        // 本周待办单量
        {
          prop: 'weekNum',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.toDoListQuantityOfThisWeek
          // width: '200px'
        },
        // 能力值（单量/周）
        {
          prop: 'abilityValue',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.capabilityValue
          // width: '200px'
        },
        // 供应商数量（新/总）
        {
          prop: 'supplierNum',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.numberOfSuppliers
          // width: '200px'
        },
        // 企业操作难度
        {
          prop: 'optDifficultyLevel',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.enterpriseOperationDifficulty,
          format: (row) => {
            if (row.optDifficultyLevel === '1') {
              return '低'
            } else if (row.optDifficultyLevel === '2') {
              return '中'
            } else if (row.optDifficultyLevel === '3') {
              return '高'
            }
          }
          // width: '200px'
        }
      ],
      columns2: [
        // 供应商名称
        {
          prop: 'creditor',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.supplierName
          // width: '200px'
        },
        // 订单数量
        {
          prop: 'orderNum',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.orderQuantity
          // width: '200px'
        },
        // 供应商类型
        {
          prop: 'enterpriseType',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.supplierType,
          format: function (row) {
            if (row.enterpriseType === '1') {
              return '总部'
            } else if (row.enterpriseType === '2') {
              return '集采'
            } else if (row.enterpriseType === '3') {
              return '分部'
            }
          }
          // width: '200px'
        },
        // 企业操作难度
        {
          prop: 'optDifficultyLevel',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.enterpriseOperationDifficulty,
          format: (row) => {
            if (row.optDifficultyLevel === '1') {
              return '低'
            } else if (row.optDifficultyLevel === '2') {
              return '中'
            } else if (row.optDifficultyLevel === '3') {
              return '高'
            }
          }
          // width: '200px'
        },
        // 保理专员
        {
          prop: 'factoringUserName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.factoringCommissioner
          // width: '200px'
        }
      ],
      columns3: [
        // 保理专员
        {
          prop: 'factoringUserName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.factoringCommissioner
          // width: '200px'
        }
      ]
    }
  },
  watch: {
    dialogVisible (value, oldVal) {
      if (value) {
        // this.$nextTick(function () {
        console.log(this.queryParas)
        this.sourceData2 = JSON.parse(JSON.stringify(this.form))
        this.loadPage = 'getAllocateDataByFactoringCommissioner'
        this.tableApi = tracemgrApi['distributionOrderDialog']
        this.$nextTick(function () {
          this.handleFilter()
        })
        // })

        // this.$nextTick(function () { this.searchData() })
      }
    }
    // ,
    // previewQueryParas (o, n) {
    //   // if (o !== n) {
    //   this.handleFilter()
    //   // }
    // }
  },
  methods: {
    handleFilter: function () {
      this.loadCount = this.loadCount + 1
    },
    distribution () {
      // alert('分配')
      if (this.chooseData2.length === 0 || this.chooseData3.length === 0) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.dataNullError)
        return
      }
      if (this.chooseData2.length < this.chooseData3.length) {
        return this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.dataError)
      }
      // let num = this.chooseData2.length / this.chooseData3.length
      // console.log(num)
      let result = []
      let tmp = []
      // 将待分配供应商列表选择的数据，根据待分配人员列表选择的列表，分成组
      for (var i = 0; i < this.chooseData2.length; i += this.chooseData3.length) {
        result.push(this.chooseData2.slice(i, i + this.chooseData3.length))
      }
      console.log(this.chooseData2.length)
      console.log(this.chooseData3.length)
      let res = []
      for (var j = 0; j < result.length; j++) {
        tmp = result[j]
        // 将每组数据中的每一个进行赋值，因为是按照选择的待分配人员列表分组，遍历时不会超出下标
        for (var a = 0; a < tmp.length; a++) {
          tmp[a].factoringUserName = this.chooseData3[a].factoringUserName
          tmp[a].factoringUserId = this.chooseData3[a].factoringUserId
          // 赋值成功后，将每一条数据写到数组，最后返回给列表
          res.push(tmp[a])
        }
        console.log(res)
        this.chooseData2 = res
      }
      console.log(result)
      this.isChoose = true
    },
    selectionData2 (value) {
      this.chooseData2 = value
    },
    selectionData3 (value) {
      this.chooseData3 = value
    },
    save () {
      if (!this.isChoose) {
        return this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.pleaseAllocateBeforeSaving)
      }
      if (this.chooseData2.length === 0 || this.chooseData3.length === 0) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.dataNullError)
        return
      }
      this.$confirm(this.$i18n.messages[this.$i18n.locale].traceMgr.saveOrNot, this.$i18n.messages[this.$i18n.locale].common.tip, {
        confirmButtonText: this.$i18n.messages[this.$i18n.locale].common.yes,
        cancelButtonText: this.$i18n.messages[this.$i18n.locale].common.no,
        type: 'warning'
      }).then(() => {
        let data = { list: this.chooseData2, orderType: this.orderType, mode: this.mode }
        tracemgrApi['distributionOrderDialog'].temporarySave(data).then(res => {
          if (res.data) {
            // this.success('保存成功')
            this.$message({
              type: 'success',
              message: this.$i18n.messages[this.$i18n.locale].common.saveSuccess
            })
            this.sourceData2 = []
            this.sourceData3 = []
            this.handler()
            this.dialogVisible = false
          } else {
            this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.saveFailedMakeSure)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$i18n.messages[this.$i18n.locale].traceMgr.canceled
        })
      })
    },
    closeDialogVisible () {
      this.sourceData2 = []
      this.sourceData3 = []
      this.spanArr = []
      this.dialogVisible = false
      this.isChoose = false
    },
    dialogClose: function () {
      this.spanArr = []
      this.sourceData2 = []
      this.sourceData3 = []
      this.chooseData2 = []
      if (this.autoClose) {
        this.$emit('close')
      } else {
        this.dialogVisible = false
      }
      this.isChoose = false
    },
    selectData (val) {
      // console.log(this.orderType)
      // this.sourceData2 = JSON.parse(JSON.stringify(val))
      // let sendData = { arrString: JSON.stringify(val), orderType: this.orderType }
      // let sendData = { pageIndex: this.queryParas.pageIndex, pageSize: this.queryParas.pageSize, orderType: this.orderType }
      // this.previewQueryParas = Object.assign({}, sendData)
      // tracemgrApi['distributionOrderDialog'].getAllocateDataByFactoringCommissioner(sendData).then(res => {
      //   this.sourceData1 = res.data.datas
      //   console.log(res.datas)
      // })
      // this.val = []
    },
    selectionData (value) {
      // 每次查询都清空这个，不然合并就会少合并，或者多合并的错乱
      this.spanArr = []
      this.sourceData3 = value
    },
    mergedCell: function ({ row, column, rowIndex, columnIndex }) {
      if (this.spanArr.length === 0) {
        this.getSpanArr()
      }
      if (columnIndex === 0) { // 对第一列进行合并
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      if (columnIndex === 1) { // 对第二列进行合并
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      if (columnIndex === 2) { // 对第三列进行合并
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      if (columnIndex === 3) { // 对第四列进行合并
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      if (columnIndex === 4) { // 对第一列进行合并
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      if (columnIndex === 5) { // 对第一列进行合并
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    getSpanArr () {
      this.spanArr = [] // 避免表格错乱！
      this.sIdx = 0
      let $this = this
      let operator = true
      let cid = ''
      this.sourceData2.forEach((item, index) => {
        item.index = index
        // $this.sourceData2[index].factoringUserName = ''
        if (index === 0) {
          $this.spanArr.push(1)
          $this.position = 0
          $this.sameRowArr.push([index])
        } else {
          // 这里是要合并行 上一个页面没有供应商名称的数据，先用区域判断一下，有数据改回来
          if ($this.sourceData2[index].creditorId === $this.sourceData2[index - 1].creditorId) {
            // 使订单数量，不因为遍历重复相加
            if (cid === $this.sourceData2[index].creditorId) {
              operator = false
            }
            let orderNumTemp = 0
            // let productName = ''
            $this.spanArr[this.position] += 1
            $this.spanArr.push(0)
            $this.sameRowArr[$this.sIdx].push(index)
            let tempArr = $this.sameRowArr[$this.sIdx]
            for (let i = 0; i < $this.sourceData2.length; i++) {
              if (operator) {
                if ($this.sourceData2[index].creditorId === $this.sourceData2[i].creditorId) {
                  orderNumTemp += $this.sourceData2[i].orderNum
                  // productName += ($this.sourceData2[i].productId) + ','
                }
              }
            }
            // productName
            if (operator) {
              $this.sourceData2[tempArr[0]].orderNum = orderNumTemp
            }
            // $this.sourceData2[tempArr[0]].productId = JSON.stringify(productName)
            cid = $this.sourceData2[index].creditorId
          } else {
            $this.spanArr.push(1)
            $this.position = index
            $this.sIdx += 1
            $this.sameRowArr.push([index])
          }
        }
      })
      cid = ''
    }
  }

}
</script>
<style scoped lang="scss">
    @import '~@/styles/tracemgr/coordinate/workbench/distributionOrderDialog.scss';
</style>
