<template>
  <div id="workSpace">
    <el-card style="position: relative;">
      <el-form label-width="100px">
        <el-row :gutter="10">
          <el-col :span="1.5">
              <el-form-item label="单据标题">
                <el-input
                  v-model.trim="queryParams.docSubject"
                  size="mini"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
            </el-col>

          <el-col :span="1.5">
              <el-form-item label="单据类型">
                <el-select multiple v-model="queryParams.modelIds" size="mini" style="width: 200px" clearable>
                  <el-option v-for="dict in dict.type.oa_templete_id" :key="dict.value" :label="dict.label" :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
        </el-row>
      </el-form>

      <div style="position: absolute;top: 18px;right: 10px;">
        <el-button type="primary" size="mini" @click="searchList">搜索</el-button>
        <el-button size="mini" plain @click="resetList">重置</el-button>
      </div>

      <div class="btn_grooup">
        <!-- <el-button type="primary" size="mini" @click="audits">批量审批</el-button> -->
      </div>

      <el-table
        v-loading="loading"
        :data="tableList" 
        fit
        :cell-style="{ borderColor: '#c0c0c0' }"
        :header-cell-style="{ borderColor: '#c0c0c0' }"
        class="exporttable"
        max-height="410"
        border
        highlight-current-row
        style="font-size: 12px;"
        @selection-change="handleSelectionChange"
        @row-click="rowSelect"
        @row-dblclick="doubleClick"
        ref="tables"
      >
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column label="序号" type="index" align="center" width="50px"/>
        <el-table-column show-overflow-tooltip label="标题" align="center" prop="docSubject"/>
        <el-table-column show-overflow-tooltip label="创建人" align="center" prop="docCreate"/>
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="180"
          >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="check(scope.row)">查看</el-button>
            <el-button type="text" size="mini" @click="audit(scope.row)">审批</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100, 200, 500]"
        :page-size="20"
        layout="total, sizes, prev, pager, next, jumper"
        :total=total>
      </el-pagination>

      <el-card class="box-card" style="margin-top: 10px;">
        <div slot="header" class="clearfix">
          <span>单据概述</span>
        </div>
        <el-table
          :data="sonTableList" 
          fit
          :cell-style="{ borderColor: '#c0c0c0' }"
          :header-cell-style="{ borderColor: '#c0c0c0' }"
          class="exporttable"
          max-height="410"
          border
          highlight-current-row
          style="font-size: 12px;"
        >
          <el-table-column label="序号" type="index" align="center" width="50px"/>
            <el-table-column v-for="(col,index) in cols" :key="index"
              :prop="col.prop"
              :label="col.label"
              :formatter="col.formatter"
            >
            </el-table-column>
        </el-table>

        <el-pagination
          background
          @size-change="sonSizeChange"
          @current-change="sonCurrentChange"
          :current-page="sonQuery.pageNum"
          :page-sizes="[10, 20, 50, 100, 200, 500]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total=sonTotal>
        </el-pagination>
      </el-card>

    </el-card>
  </div>
</template>

<script>
import { getWorkSpaceList, auditWork, getWorkDetailList } from '@/api/purchase/workSpace.js'
export default {
  name: 'workSpace',
  dicts: ['oa_templete_id'],
  data() {
    return {
      queryParams: {
        modelIds:[],
        docSubject: '',
        pageNum: 1,
        pageSize: 20
      },
      loading: false,
      tableList: [],
      total: 0,
      ids: [],
      sonTableList: [],
      sonQuery: {
        pageNum: 1,
        pageSize: 10
      },
      sonTotal: 0,
      checkRow: {
        billCode: '',
        type: ''
      },
      cols: [
        {label: '物料编码',  prop: 'materialCode'},
        {label: '物料名称',  prop: 'materialName'},
        {label: '规格',  prop: 'specification'},
        {label: '型号',  prop: 'model'},
        {label: '单位',  prop: 'unitName'},
        {label: '生产厂家/代理人',  prop: 'manufacturerName'},
        {label: '调出仓库',  prop: 'deliveryWarehouseName'},
        {label: '调出货位',  prop: 'deliveryAllocationName'},
        {label: '数量',  prop: 'qty'},
        {label: '调入仓库',  prop: 'storageWarehouseName'},
        {label: '调入货位',  prop: 'storageAllocationName'},
      ],
      // 记录点击行的下标
      recordIndex: '',
    }
  },
  created() {
    this.getList(this.queryParams)
  },
  methods: {
    getList(params){
      getWorkSpaceList(params).then(res => {
        if (res.code === 200) {
          this.tableList = res.rows
          this.total = res.total
        }
      }).then(() => {
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    },
    searchList() {
      this.getList(this.queryParams)
    },
    resetList() {
      this.queryParams = {
        modelIds:[],
        docSubject: '',
        pageNum: 1,
        pageSize: 20
      }
      this.searchList()
    },
    handleSelectionChange(selection) {
      console.log('选中', selection)
      this.ids = selection
      // console.log('选中数组', this.ids.join())
    },
    doubleClick(row) {
      // this.$refs.tables.toggleRowSelection(row);
      this.rowSelect(row)
    },
    rowSelect(row, column, event) {
      // console.log('行信息', row)
      // this.recordIndex = this.tableList.findIndex((value, index ,arr) => {
      //   return value.billCode == row.billCode
      // })
      // console.log('下标:', this.recordIndex)
      // this.check(row)
      // 选择行存储便于子表分页
      this.checkRow = row
      // 采购需求单
      if(row.type == 'PU_DEMAND_RULE') {
        this.cols = [
          {label: '物料编码',  prop: 'materialCode'},
          {label: '物料名称',  prop: 'materialName'},
          {label: '规格',  prop: 'specification'},
          {label: '型号',  prop: 'model'},
          {label: '单位',  prop: 'unitName'},
          {label: '生产厂家/代理人',  prop: 'manufacturerName'},
          {label: '实际（业务）需求量',  prop: 'qty'},
          {label: '月均销量',  prop: 'averageQtyMonth'},
          {label: '需求可用周期',  prop: 'demandPeriod'},
          {label: '业务备注',  prop: 'remark'},
          {label: '紧急标识',  prop: 'isUrgency',
            formatter: function(row, column, cellValue, index) {
              return row.isUrgency == 'Y' ? '是' : '否'
            }
          },
          {label: '补单标识',  prop: 'isReplenishment',
            formatter: function(row, column, cellValue, index) {
              return row.isReplenishment == 'Y' ? '是' : '否'
            }
          },
        ]
        // 调拨订单
      } else if (row.type == 'ALLOT_RULE') {
        this.cols = [
          {label: '物料编码',  prop: 'materialCode'},
          {label: '物料名称',  prop: 'materialName'},
          {label: '规格',  prop: 'specification'},
          {label: '型号',  prop: 'model'},
          {label: '单位',  prop: 'unitName'},
          {label: '生产厂家/代理人',  prop: 'manufacturerName'},
          {label: '调出仓库',  prop: 'deliveryWarehouseName'},
          {label: '调出货位',  prop: 'deliveryAllocationName'},
          {label: '数量',  prop: 'qty'},
          {label: '调入仓库',  prop: 'storageWarehouseName'},
          {label: '调入货位',  prop: 'storageAllocationName'},
        ]
        // 物料申请单
      } else if (row.type == 'MATERIAL_APPLY_RULE') {
        this.cols = [
          {label: '物料一级分类',  prop: 'classOneName'},
          {label: '物料基本分类',  prop: 'classifyName'},
          {label: '物料名称',  prop: 'materialName'},
          {label: '型号',  prop: 'model'},
          {label: '规格',  prop: 'specification'},
          {label: '生产厂家/代理人',  prop: 'manufacturerName'},
          {label: '注册证号',  prop: 'registrationNo'},
          {label: '注册人',  prop: 'registrant'},
          {label: '存储条件',  prop: 'storageCondition'},
          {label: '运输条件',  prop: 'transportationCondition'},
          {label: '是否医药物料',  prop: 'isMedicine',
            formatter: function(row, column, cellValue, index) {
              return row.isMedicine == '0' ? '是' : '否'
            }
          },
          {label: '是否药品',  prop: 'isDrug',
            formatter: function(row, column, cellValue, index) {
              return row.isDrug == '0' ? '是' : '否'
            }
          },
        ]
        // 价格申报单
      } else if (row.type == 'PU_PRICE_APPLY_RULE') {
        this.cols = [
          {label: '物料编码',  prop: 'materialCode'},
          {label: '物料名称',  prop: 'materialName'},
          {label: '型号',  prop: 'model'},
          {label: '规格',  prop: 'specification'},
          {label: '生产厂家/代理人',  prop: 'manufacturerName'},
          {label: '含税单价',  prop: 'taxPrice'},
          {label: '最近价格',  prop: 'recentlyPrice'},
          {label: '单价差',  prop: 'priceDiffer'},
          {label: '客户',  prop: 'customerName'},
          {label: '供应商名称1',  prop: 'supplierName1'},
          {label: '单价1',  prop: 'unitPrice1'},
        ]
        // 采购订单
      } else if (row.type == 'PU_ORDER_RULE') {
        this.cols = [
          {label: '收货客户',  prop: 'customerName'},
          {label: '物料编码',  prop: 'materialCode'},
          {label: '物料名称',  prop: 'materialName'},
          {label: '生产厂家',  prop: 'manufacturerName'},
          {label: '医药物料',  prop: 'isMedcine'},
          {label: '数量',  prop: 'qty'},
          {label: '含税单价',  prop: 'taxPrice'},
          {label: '价税合计',  prop: 'money'},
          {label: '赠品',  prop: 'isGift',
            formatter: function(row, column, cellValue, index) {
              return row.isGift == 'Y' ? '是' : '否'
            }        
          },
          {label: '折扣%',  prop: 'nitemdiscountrate'},
          {label: '价格类型',  prop: 'priceType'},
        ]
      }
      this.getDetailList(this.checkRow)
    },
    audits() {
      if(this.ids.length == 0) {
        this.$modal.notifyWarning("请选中至少一条数据");
      } else {
        this.$modal.confirm('确认审批选中单据?').then(() => {
        this.$modal.loading("审批中...");
        auditWork(this.ids).then(res => {
          if (res.code === 200) {
            this.$modal.closeLoading();
            this.$modal.notifySuccess("审批成功");
            this.searchList()
            this.sonTableList = []
          }
        })
        }).catch(() => {
          this.$modal.closeLoading();
          this.searchList()
          this.sonTableList = []
        })
      } 
    },
    check(row) {
      console.log(row)
      this.$router.push({path: row.linkUrl ,query: {billCode: row.billCode}})
    },
    audit(row) {
      this.$modal.loading("审批中...");
      auditWork([row]).then(res => {
        if(res.code === 200) {
          this.$modal.closeLoading();
          this.$modal.notifySuccess("审批成功");
          this.searchList()
          this.sonTableList = []
        }
      })
      // .then(() => {
      //   this.$refs.tables.setCurrentRow(this.tableList[this.recordIndex])
      //   let param = {
      //     billCode: this.tableList[this.recordIndex].billCode,
      //     type: this.tableList[this.recordIndex].type,
      //     ...this.sonQuery
      //   }
      //   getWorkDetailList(param).then(res => {
      //     if(res.code === 200) {
      //       this.sonTableList = res.rows
      //       this.sonTotal = res.total
      //     }
      //   }).catch(err => {
      //   })
      // })
      .catch(() => {
        this.$modal.closeLoading();
        this.searchList()
        this.sonTableList = []
      })
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList(this.queryParams)
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList(this.queryParams)
    },
    sonSizeChange(val) {
      this.sonQuery.pageSize = val
      this.getDetailList(this.checkRow)
    },
    sonCurrentChange(val) {
      this.sonQuery.pageNum = val
      this.getDetailList(this.checkRow)
    },
    // 获取单据概述列表
    getDetailList (row) {
      this.$modal.loading("加载中...");
      let param = {
        billCode: row.billCode,
        type: row.type,
        ...this.sonQuery
      }
      getWorkDetailList(param).then(res => {
        if(res.code === 200) {
          this.sonTableList = res.rows
          this.sonTotal = res.total
          this.$modal.closeLoading();
        }
      }).catch(err => {
        this.$modal.closeLoading();
      })
    },
  }
}
</script>

<style lang="scss" scoped>
#workSpace {
  padding: 12px;
  box-sizing: border-box;
  overflow-y: scroll;
}
.btn_grooup {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}
.el-pagination {
  margin-top: 10px;
  text-align: right;
}
</style>
<style>
.exporttable {
  border: solid 1px #c0c0c0;
}
.el-table .el-table__header-wrapper th {
  font-size: 14px;
}
</style>