<template>
  <!-- 待审核 -->
  <div id="approval-wrap">
    <div class="table-operations">
      <a-button type="add" @click="approvalForm" :disabled="selectedRows.length === 0">审批</a-button>
      <a-button type="view" @click="getShowPopup('log')" :disabled="!oneHasSelected">审批日志</a-button>
      <a-button type="delete" @click="getShowPopup('contrast')" :disabled="!operationTypeState">数据对比</a-button>
    </div>
    <div class="table-content">
      <a-table
        ref="table"
        :pagination="{
          total:total,
          'show-less-items':true,
          'show-quick-jumper':true,
          'onChange':onPageChange,
          'hideOnSinglePage':true
        }"
        :columns="columns"
        :dataSource="dataSource"
        :customRow="customRow"
        :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        :scroll="{x:xscroll}">
        <template slot="processStatus" slot-scope="text, record">
          <a-radio-group @change="processStatusOnChange(record)" v-model="record.processStatus">
            <a-radio :value="3">
              通过
            </a-radio>
            <a-radio :value="4">
              驳回
            </a-radio>
          </a-radio-group>
        </template>

        <template slot="approveDesc" slot-scope="text, record">
          <div id="approveDescBox">
            <div class="approveDescBar">
              <span>{{ record.approveDesc }}</span>
              <a-icon type="edit" v-if="selectedRows.length !== 0" @click="approveDescEdit(record)" />
            </div>
            <div class="table-search-bar" v-if="approveDescBarState === record.key">
              <a-input type="textarea" placeholder="" v-model="NewApproveDesc" />
              <div class="btn-list">
                <a-button type="primary" size="small" @click="handleSubmit(record)">
                  确定
                </a-button>
                <a-button size="small" @click="handleReset(record)">
                  重置
                </a-button>
              </div>
            </div>
          </div>
        </template>
      </a-table>
    </div>
    <a-modal class="popupBox" v-model="showPopup" :title="popupTitle" :footer="null">
      <Journal v-if="popupTitle === '审批日志'" :columns="logColumns" :params="params" @handleOk="handleOk" />
      <DataContrast
        v-if="popupTitle === '数据对比'"
        :params="params"
        :selectedRows="selectedRows"
        :dataContrastColumns="dataContrastColumns"
        :showPopup="showPopup"
        @handleOk="handleOk" />
    </a-modal>

  </div>
</template>

<script type="text/ecmascript-6">
import FilterTable from '@/components/filterTable'
import Journal from './Journal'
import DataContrast from './DataContrast'
import { getApproveDatas, getTOApproveList } from '@/api/auditMasterData/approve'
export default {
  components: {
    FilterTable,
    Journal,
    DataContrast
  },
  props: {
    columns: {
      type: Array,
      required: true
    },
    logColumns: {
      type: Array,
      required: true
    }
  },
  computed: {
    oneHasSelected() {
      return this.selectedRowKeys.length === 1
    },
    operationTypeState() {
      return this.operationType === '变更' && this.operationType !== ''
    }
  },
  data() {
    return {
      total: 0,
      dataSource: [],
      selectedRowKeys: [],
      selectedRows: [],
      approveDescBarState: null, //
      NewApproveDesc: '',
      params: {
        modelId: null,
        pageSize: 10,
        pageNum: 1
      },

      // 日志
      showPopup: false,
      popupTitle: '',

      // 数据对比
      operationType: '',
      dataContrastColumns: [],
      // dataContrastSource: [],
      xscroll: 1300
    }
  },
  mounted() {
    this.params.modelId = this.$route.query.id
    this.getTOApproveList() // 待审批表数据
  },
  methods: {
    // 审批
    approvalForm() {
      var that = this
      var approveDatas = this.selectedRows
      approveDatas.forEach((item) => {
        item.modelId = this.params.modelId
      })
      // console.log('审批selectedRows:', this.selectedRows)

      this.$confirm({
        title: '确认审批所选中数据?',
        onOk() {
          return getApproveDatas(approveDatas).then((res) => {
            if (res.code === 200) {
              that.getTOApproveList()
              that.$EventBus.$emit('changeApproved')

              that.clearSelectedRows()
              that.$message.success('审批成功', 3)
            }
          })
        },
        onCancel() {}
      })
    },

    // 审批日志 && 数据对比
    getShowPopup(e) {
      this.showPopup = false
      this.selectedRows.forEach((item) => {
        this.params.recordId = item.recordId
        this.params.id = item.id
      })
      if (e === 'log') {
        this.popupTitle = '审批日志'

        // console.log('审批日志this.params:', this.params)
      } else if (e === 'contrast') {
        this.popupTitle = '数据对比'
        this.columns.slice(4, -4).forEach((item) => {
          var obj = {}
          obj.name = item.title
          obj.key = item.key
          this.dataContrastColumns.push(obj)
        })
      }
      this.showPopup = true
    },
    handleOk(i) {
      this.showPopup = false
      if (i === 0) {
        this.getTOApproveList()
      } else if (i === 1) {
        this.showPopup = false
      }
    },

    // 数据对比
    dataComparisonFun() {},

    // 审批结果
    processStatusOnChange(record) {
      switch (record.processStatus) {
        case '':
          record.approveDesc = ''
          break
        case 3:
          record.approveDesc = '通过'
          break
        case 4:
          record.approveDesc = '驳回'
          break
      }
      this.selectedRowKeys.push(record.key)
      this.selectedRows.push(record)
      // console.log('radio checked  this.selectedRowKeys: ', this.selectedRowKeys)
      // console.log('radio checked  this.selectedRows: ', this.selectedRows)
    },

    // 选择行
    onSelectChange(selectedRowKeys, selectedRows) {
      this.dataSource.forEach((item, index) => {
        item.processStatus = ''
        item.approveDesc = ''
      })
      selectedRows.forEach((item, index) => {
        item.processStatus = 3
        item.approveDesc = '通过'
      })
      if (selectedRows.length === 1) {
        selectedRows.forEach((item, index) => {
          this.operationType = item.operationType
        })
      } else {
        this.operationType = ''
      }
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      // console.log('选择行this.selectedRowKeys: ', this.selectedRowKeys)
      // console.log('选择行this.selectedRows: ', this.selectedRows)
    },

    // 修改审批意见
    approveDescEdit(record) {
      this.approveDescBarState = record.key
      this.NewApproveDesc = record.approveDesc
    },
    // 修改审批意见——确定
    handleSubmit(record) {
      record.approveDesc = this.NewApproveDesc
      this.approveDescBarState = null
      this.NewApproveDesc = ''
      console.log('record: ', record)
      // console.log('radio checked  this.selectedRows: ', this.selectedRows)
    },
    // 修改审批意见——重置
    handleReset(record) {
      this.NewApproveDesc = record.approveDesc
    },
    // 待审批表数据
    getTOApproveList() {
      getTOApproveList(this.params).then((res) => {
        if (res.rows !== undefined) {
          const resRows = res.rows
          const dataSource = []
          resRows.forEach((item, index) => {
            item.operationType = this.operationTypeFun(item.operationType)
            item.key = index + 1
            const logJson = JSON.parse(item.logJson)

            this.total = res.total
            dataSource.push(Object.assign(item, logJson))
          })
          this.dataSource = dataSource
          // console.log('待审批表数据this.dataSource: ', res)
        }
      })
    },
    operationTypeFun(operationType) {
      switch (operationType) {
        case '0':
          operationType = '新增'
          break
        case '1':
          operationType = '变更'
          break
        case '2':
          operationType = '启用'
          break
        case '3':
          operationType = '停用'
          break
        case '4':
          operationType = '删除'
          break
      }
      return operationType
    },

    // 日期格式化
    myformatdate(inputTime) {
      if (!inputTime && typeof inputTime !== 'number') {
        return ''
      }
      var localTime = ''
      inputTime = new Date(inputTime).getTime()
      const offset = new Date().getTimezoneOffset()
      localTime = new Date(inputTime - offset * 60000).toISOString()
      localTime = localTime.substr(0, localTime.lastIndexOf('.'))
      localTime = localTime.replace('T', ' ')
      return localTime
    },
    changeParams(key, value) {
      this.$set(this.params, key, value)
    },

    // 表格行颜色
    customRow(record, index) {
      return {
        style: {
          // 字体颜色
          color: record.remarkDesc ? record.remarkDesc.fontColor : '#262626',
          // 行背景色
          'background-color': index % 2 === 0 ? '#FFFFFF' : '#FAFAFA'
        }
      }
    },

    clearSelectedRows() {
      const selectedRowKeys = []
      const selectedRows = []
      this.onSelectChange(selectedRowKeys, selectedRows)
      // console.log('清空啦！！！！！')
    },
    onPageChange(e) {
      console.log(`e`, e)
      this.clearSelectedRows()
    }
  },
  watch: {
    columns: {
      deep: true,
      immediate: true,
      handler(val) {
        const length = this.columns.length
        if (length > 9) {
          this.xscroll = this.columns.length * 200 - 400
        }
      }
    }
  }
}
</script>
<style lang='less'>
.popupBox {
  .ant-modal {
    width: 1200px !important;
  }
}
</style>
<style lang='less' scoped>
#approval-wrap {
  .table-operations {
    margin: 5px 0 15px;
  }
  #approveDescBox {
    position: relative;
    .approveDescBar {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .table-search-bar {
      position: absolute;
      z-index: 99;
      background: #fff;
      opacity: 1;
      .btn-list {
        margin-top: 10px;
        & > button:nth-child(2) {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
