<template>
  <div class="list">
    <el-row class="list__operation">
      <div class="operation__btn" v-if="mode !== 'detail'">
        <el-button v-auth="50410010216" type="primary" @click="toAdd">添加</el-button>
        <template v-if="formData.cdRuleQcDetailList.length">
          <el-button v-auth="50410010213" type="primary" needconfirm @click="e => operate(e, 'deleteSuggest')">删除</el-button>
        </template>
      </div>
    </el-row>
    <el-table
      ref="table"
      stripe
      border
      :data="formData.cdRuleQcDetailList"
      @selection-change="selectionChange"
      @row-click="toCheck"
    >
      <table-column type="selection" fixed align="center"></table-column>
      <table-column label="行号" prop="lineNo" :formatter="formatColumn"></table-column>
      <table-column label="合格率区间从(大于)" prop="fmRate"></table-column>
      <table-column label="合格率区间到(小于)" prop="toRate"></table-column>
      <table-column label="质检处理建议" prop="qcSuggest">
        <template slot-scope="scope">
          {{ $utils.keyMatcher(scope.row.qcSuggest, $keys.strategy.qcRules.qcSuggest).name }}
        </template>
      </table-column>
      <table-column label="备注" prop="remark" :formatter="formatColumn"></table-column>
      <table-column label="操作" width="100" fixed="right" v-if="mode !== 'detail'">
        <template slot-scope="scope">
          <el-button
            v-auth="50600010105"
            size="mini"
            type="primary"
            icon="el-icon-edit"
            plain
            circle
            @click.stop="toEdit(scope.row, scope.$index)"
          ></el-button>
          <el-button
            v-auth="50600010111"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            plain
            circle
            @click.stop="toDelete(scope.row, scope.$index)"
          ></el-button>
        </template>
      </table-column>
    </el-table>
    <el-pagination
      class="pagination"
      @size-change="sizeChange"
      @current-change="currentChange"
      :current-page="currentNo"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <SuggestCreator
      :mainFormData="formData"
      :showCreator="showCreator"
      :detailData="detailData"
      :selectedIndex="selectedIndex"
      @close="showCreator = false"
      @createDone="setSuggestList"
    />
  </div>
</template>

<script>
import SuggestCreator from './SuggestCreator'
export default {
  components: { SuggestCreator },
  props: ['formData', 'mode', 'needGetList'],
  created () {
  },
  mounted () {
  },
  watch: {
    needGetList: {
      handler (val) {
        val && this.getSuggestList()
      },
    }
  },

  data () {
    return {
      currentNo: 1,
      pageSize: 10,
      total: 0,
      detailData: {}, // 详情数据
      suggestList: [], // 质检处理建议列表
      showCreator: false, // 显示新增框
      selectedIndex: undefined, // 选中的行index
      selection: [], // 勾选的项目
    }
  },
  methods: {
    // 获取建议列表
    getSuggestList (query = {}) {
      const url = this.$API.strategy.qcRules.getSuggestList
      const param = {
        ruleCode: this.formData.ruleCode,
        'page.currentPage': this.currentNo,
        'page.limitCount': this.pageSize,
        ...query,
      }
      this.$https.post(url, param)
        .then(data => {
          this.total = data.total
          this.formData.cdRuleQcDetailList = data.rows
        })
    },
    // 点击表格行
    toCheck (row) {
      this.$refs.table.toggleRowSelection(row)
    },
    // 页码变化
    currentChange (currentNo) {
      this.currentNo = currentNo
      const query = { 'page.currentPage': currentNo }
      this.getSuggestList(query)
    },
    // 每页条数变化
    sizeChange (pageSize) {
      this.pageSize = pageSize
      const query = { 'page.limitCount': pageSize }
      this.getSuggestList(query)
    },
    // 新增
    toAdd () {
      this.detailData = {}
      this.selectedIndex = undefined
      this.showCreator = true
    },
    // 编辑
    toEdit (row, index) {
      this.detailData = row
      this.selectedIndex = index
      this.showCreator = true
    },
    // 添加数据
    setSuggestList (obj, $index) {
      // 修改时使用 $index, 新增时没有 $index 则使用 length
      const index = $index !== undefined ? $index : this.formData.cdRuleQcDetailList.length
      this.formData.cdRuleQcDetailList.splice(index, 1, obj)
      this.setLineNoCache()
    },
    // 设置缓存行号
    setLineNoCache () {
      const length = this.formData.cdRuleQcDetailList.length
      for (let index = 0; index < length; ++index) {
        this.formData.cdRuleQcDetailList[index].lineNoCache = this.formatLineNoCache(index)
      }
    },
    // 格式化缓存行号
    formatLineNoCache (index) {
      let baseNo = ((index + 1) / 1000).toString().replace('.', '')
      const diff = 4 - baseNo.length
      for (let i = 0; i < diff; ++i) {
        baseNo += '0'
      }
      return baseNo
    },
    // 删除
    toDelete (row, index) {
      this.$confirm(`确认要删除吗 ?`)
        .then(() => {
          if (row.lineNo) {
            const url = this.$API.strategy.qcRules.deleteSuggest
            const param = {
              ruleCode: this.formData.ruleCode,
              lineNos: row.lineNo,
            }
            this.$https.post(url, param)
              .then(() => {
                this.$emit('deleteItems', [row])
              })
          }
          this.formData.cdRuleQcDetailList.splice(index, 1)
          this.setLineNoCache()
        })
    },
    // 批量删除
    multiDelete () {
      this.selection.map(item => {
        this.formData.cdRuleQcDetailList.some((listItem, listIndex) => {
          if (listItem.lineNoCache === item.lineNoCache) {
            this.formData.cdRuleQcDetailList.splice(listIndex, 1)
          }
          return listItem.lineNoCache === item.lineNoCache
        })
      })
      this.setLineNoCache()
    },
    // 勾选变化
    selectionChange (selection) {
      this.selection = selection
    },
    // 检查勾选
    checkSelections () {
      if (!this.selection.length) {
        this.$message.error('请选择记录')
        return false
      }
      return true
    },
    // 操作弹窗后确认
    operateConfirm (type) {
      const databaseItems = this.selection.filter(item => item.lineNo)
      const lineNos = databaseItems.map(item => item.lineNo).join(',')
      if (lineNos) {
        const url = this.$API.strategy.qcRules[type]
        const param = {
          ruleCode: this.formData.ruleCode,
          lineNos,
        }
        this.$https.post(url, param)
          .then(() => {
            this.$emit('deleteItems', databaseItems)
          })
      }
      this.multiDelete()
    },
  },
}
</script>

<style lang="scss" scoped>
  .pagination {
    margin-top: 20px;
  }
  .list__operation {
    padding-bottom: 20px;
    .operation__btn {
      float: left;
    }
    .operation__msg {
      float: right;
    }
  }
  .detail-no {
    color: #0682ea;
    &:hover {
      cursor: pointer;
    }
  }
</style>
