<template>
  <div class="app-container">
    <el-card style="height: 850px">
      <div style="margin-top: 7px; margin-bottom: 7px">
        <el-select
          v-model="orderNumberTypeValue"
          :remote-method="getOrderNumberType"
          style="width:200px"
          placeholder="订单号"
          size="small"
          filterable
          clearable
          remote
          @change="pageCurrent=1;searchTable();getProductName()">
          <el-option
            v-for="item in orderNumberType"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <el-select
          v-model="productNameValue"
          style="width:200px"
          placeholder="产品名称"
          size="small"
          filterable
          clearable
          @change="pageCurrent=1;searchTable()">
          <el-option
            v-for="item in productName"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <el-input
          v-model="purchasePartValue"
          style="width:100px"
          placeholder="名称"
          size="small"
          filterable
          clearable
          @keyup.enter.native="pageCurrent=1;searchTable()"/>
        <el-input
          v-model="purchaseModel"
          style="width:150px"
          placeholder="图号/型号"
          size="small"
          filterable
          clearable
          @keyup.enter.native="pageCurrent=1;searchTable()"/>
        <el-select
          v-model="purchasingStatusValue"
          style="width:100px"
          placeholder="采购状态"
          size="small"
          filterable
          clearable
          @change="pageCurrent=1;searchTable()">
          <el-option
            v-for="item in purchasingStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <span style="font-size: 13px;color: black;margin-left: 20px">采购时间</span>
        <el-date-picker
          v-model="dateRange"
          size="small"
          type="daterange"
          align="center"
          style="width: 240px;"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="pageCurrent=1;searchTable"/>
        <el-button type="success" size="mini" style="margin-left: 20px" @click="exportExcel()">导出</el-button>
        <el-button
          v-show="Number(token)===2"
          icon="el-icon-thumb"
          type="warning"
          plain
          size="small"
          style="margin-left: 10px;margin-right: 20%"
          @click="finish()">手动完成
        </el-button>
        <el-badge :value="numberModifyPurchase" class="item">
          <el-button type="text" size="small" @click="viewModifyOrder()">手动完成记录</el-button>
        </el-badge>
      </div>
      <div>
        <el-table
          v-loading="loading"
          ref="table"
          :data="tableData"
          :summary-method="getSummaries"
          highlight-current-row
          show-summary
          border
          stripe
          size="small"
          style="width: 1681px"
          height="740px"
          @sort-change="sortChange"
          @row-click="searchTable1">
          <el-table-column
            :width="setColumnWidth('状态')"
            label="采购状态"
            align="center"
            prop="采购状态"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.采购状态 }}
            </template>
          </el-table-column>
          <el-table-column label="采购件" align="center" sortable="custom" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.采购件 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('图号或型号')" label="图号/型号" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.图号或型号 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('材料')" label="材料" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.材料 }}
            </template>
          </el-table-column>
          <el-table-column width="63px" label="采购数" align="center" prop="采购数" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.采购数 }}
            </template>
          </el-table-column>
          <el-table-column width="73px" label="用库存数" align="center" prop="使用库存数" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.使用库存数 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('单位')" label="单位" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.单位 }}
            </template>
          </el-table-column>
          <el-table-column width="70px" label="单价" align="center" show-overflow-tooltip prop="单价">
            <template slot-scope="scope">
              {{ scope.row.单价 ? Number(scope.row.单价).toFixed(2) : '' }}
            </template>
          </el-table-column>
          <el-table-column width="70px" label="最新单价" align="center" show-overflow-tooltip prop="历史单价">
            <template slot-scope="scope">
              {{ scope.row.历史单价 ? Number(scope.row.历史单价).toFixed(2) : '' }}
            </template>
          </el-table-column>
          <el-table-column width="63px" label="到货数" align="center" prop="到货数" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.到货数 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('采购备注')" label="采购备注" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.采购备注 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('订单备注')" label="订单备注" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.订单备注 }}
            </template>
          </el-table-column>
          <el-table-column width="120px" label="采购合同号" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.合同号 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('供应商')" label="供应商" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.供应商 }}
            </template>
          </el-table-column>
          <el-table-column width="123px" label="订单号" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.订单号 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('产品名称')" label="产品名称" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.产品名称 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('日期')" label="交货日期" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.到货日期 }}
            </template>
          </el-table-column>
          <el-table-column
            :width="setColumnWidth('任务下达')"
            label="任务下达"
            align="center"
            sortable
            prop="任务下达"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.任务下达 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('日期')" label="采购日期" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.采购日期 }}
            </template>
          </el-table-column>
          <el-table-column :width="setColumnWidth('日期')" label="采购期限" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.采购期限 }}
            </template>
          </el-table-column>
        </el-table>
        <div class="block" style="margin: 10px 0;">
          <el-pagination
            :current-page="pageCurrent"
            :page-sizes="[10, 20, 30, 40, 100]"
            :page-size="pageSize"
            :total="total"
            :pager-count="5"
            style="display:inline-block;width:50%"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChanges"
            @current-change="handleCurrentChanges"/>
        </div>
      </div>
    </el-card>
    <el-dialog
      v-el-drag-dialog
      :visible.sync="dialogFormVisiblePurchase"
      center
      title="查看手动完成记录"
      width="50%">
      <el-table
        :data="tableDataVisibleModifyPurchase"
        :header-cell-style="{background: '#383E4B',color: 'white'}"
        border
        stripe
        size="small"
        height="550px"
        style="width: 1000px">
        <el-table-column label="采购件" align="center">
          <template slot-scope="scope">
            {{ scope.row.采购件 }}
          </template>
        </el-table-column>
        <el-table-column label="图号/型号" align="center">
          <template slot-scope="scope">
            {{ scope.row.图号或型号 }}
          </template>
        </el-table-column>
        <el-table-column min-width="90px" label="修改人" align="center">
          <template slot-scope="scope">
            {{ scope.row.姓名 }}
          </template>
        </el-table-column>
        <el-table-column width="160px" label="手动完成时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.修改时间 }}
          </template>
        </el-table-column>
        <el-table-column min-width="50px" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh-left"
              style="color: #ff6c00"
              @click="repealOk(scope.row)">撤销完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      typeValue: '', // 类型
      type: [], // 类型数组
      productNameValue: '', // 产品名称
      productName: [], // 产品名称数组
      orderNumberTypeValue: '', // 订单号
      orderNumberType: [], // 订单号数组
      purchasePartValue: '', // 采购件名称
      purchaseModel: '', // 采购图号/型号
      purchasePart: [], // 采购件数组
      PartType: '通用库存',
      purchasingStatusValue: '', // 采购状态名称
      purchasingStatus: [], // 采购状态数组
      dateRange: '', // 提交日期
      materialNameTypeValue: '', // 物料名称规格型号
      dialogFormVisiblePurchase: false, // 采购手动完工记录弹窗
      tableDataVisibleModifyPurchase: [], // 采购手动完工记录数据
      numberModifyPurchase: '',
      tableClickRow: null,
      contractState: [
        {
          value: 2,
          label: '未提交'
        }, {
          value: 1,
          label: '提交'
        }
      ], // 合同状态数组
      loading: false, // 数据加载
      total: 0, // 分页总数
      tableData: [], // 合同信息表
      pageCurrent: 1, // 分页当前页
      pageSize: 30, // 分页每页显示条数
      orderName: '', // 排序列名
      order: '' // 排序方式
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'token'
    ])
  },
  updated() {
    this.$nextTick(() => {
      this.$refs['table'].doLayout()
    })
  },
  created() {
    this.searchTable()
    this.getPurchasingStatus()
    this.getOrderNumberType('')
    this.viewModifyPurchaseClick()
  },
  methods: {
    finish() {
      if (this.tableClickRow) {
        if (this.tableClickRow.采购状态 === '已到') {
          this.$message.warning('当前采购件已到，不可再次完成')
          return
        }
        this.$confirm('是否要手动完成该采购订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var param = []
          param[0] = ['标准件和外购件流水号', this.tableClickRow.流水号]
          param[1] = ['采购合同明细流水号', this.tableClickRow.采购合同明细流水号]
          param[2] = ['修改人', this.id]
          var Data = this.CreateData('12', '采购管理_手动完成', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              this.$message.success('完成成功')
              this.searchTable()
              this.viewModifyPurchaseClick()
            } else {
              this.$message.error('完成失败')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        this.$message.warning('请选择要手动完成的的采购订单！')
      }
    },

    getOrderNumberType(query) {
      this.orderNumberType = []
      var param = []
      param[0] = ['订单编号', query]
      var Data = this.CreateData('11', '订单信息_列表_查询数据_bak', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.orderNumberType.push({
            label: response.data[i].订单编号,
            value: response.data[i].订单流水号
          })
        }
      })
    },
    getProductName() {
      this.productName = []
      if (this.orderNumberTypeValue) {
        var param = []
        param[0] = ['订单流水号', this.orderNumberTypeValue]
        var Data = this.CreateData('11', '订单信息_产品信息_查询数据', param)
        this.ExecDatabase(Data).then(response => {
          for (let i = 0; i < response.data.length; i++) {
            this.productName.push({
              label: response.data[i].产品名称,
              value: response.data[i].组件流水号
            })
          }
        })
      }
    },
    searchTable1(row) {
      console.log('订单查询点击的行', row)
      this.tableClickRow = row
    },
    viewModifyOrder() {
      this.dialogFormVisiblePurchase = true
    },
    viewModifyPurchaseClick() {
      var param1 = []
      var Data1 = this.CreateData('11', '采购管理_手动完成记录_视图_查询', param1)
      this.ExecDatabase(Data1).then(response => {
        this.numberModifyPurchase = response.data.length
        this.tableDataVisibleModifyPurchase = response.data
      })
    },
    getPurchasingStatus() {
      var param = []
      var Data = this.CreateData('11', '采购管理_采购合同明细_采购状态_查询数据', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.purchasingStatus.push({
            label: response.data[i].采购状态名称,
            value: response.data[i].采购状态流水号
          })
        }
      })
    },
    searchTable() {
      this.tableClickRow = null
      let dateRange_check, orderNumberTypeValue_check, purchasePartValue_check, productNameValue_check,
        purchasingStatusValue_check, purchaseModel_check
      this.dateRange ? dateRange_check = 1 : (dateRange_check = 0, this.dateRange = '')
      this.orderNumberTypeValue ? orderNumberTypeValue_check = 1 : orderNumberTypeValue_check = 0
      this.purchasePartValue ? purchasePartValue_check = 1 : purchasePartValue_check = 0
      this.purchaseModel ? purchaseModel_check = 1 : purchaseModel_check = 0
      this.productNameValue ? productNameValue_check = 1 : productNameValue_check = 0
      this.purchasingStatusValue ? purchasingStatusValue_check = 1 : purchasingStatusValue_check = 0
      var param = []
      param[0] = ['订单流水号_check', orderNumberTypeValue_check]
      param[1] = ['订单流水号', this.orderNumberTypeValue]
      param[2] = ['组件流水号_check', productNameValue_check]
      param[3] = ['组件流水号', this.productNameValue]
      param[4] = ['采购状态_check', purchasingStatusValue_check]
      param[5] = ['采购状态', this.purchasingStatusValue]
      param[6] = ['采购件_check', purchasePartValue_check]
      param[7] = ['采购件', this.purchasePartValue]
      param[8] = ['图号_check', purchaseModel_check]
      param[9] = ['图号', this.purchaseModel]
      param[10] = ['时间_check', dateRange_check]
      param[11] = ['开始时间', this.dateRange[0]]
      param[12] = ['结束时间', this.dateRange[1]]
      param[13] = ['排序名称', this.orderName]
      param[14] = ['排序方式', this.order]
      var Data = this.CreateData('11', '采购管理_采购件_查询数据', param, this.pageSize, this.pageCurrent)
      this.ExecDatabase(Data).then(response => {
        this.tableData = response.data.rows
        this.total = response.data.total
      })
    },
    exportExcel() {
      if (this.tableData.length !== 0) {
        let dateRange_check, orderNumberTypeValue_check, purchasePartValue_check, productNameValue_check,
          purchasingStatusValue_check, purchaseModel_check
        this.dateRange ? dateRange_check = 1 : (dateRange_check = 0, this.dateRange = '')
        this.orderNumberTypeValue ? orderNumberTypeValue_check = 1 : orderNumberTypeValue_check = 0
        this.purchasePartValue ? purchasePartValue_check = 1 : purchasePartValue_check = 0
        this.purchaseModel ? purchaseModel_check = 1 : purchaseModel_check = 0
        this.productNameValue ? productNameValue_check = 1 : productNameValue_check = 0
        this.purchasingStatusValue ? purchasingStatusValue_check = 1 : purchasingStatusValue_check = 0
        var param = []
        param[0] = ['订单流水号_check', orderNumberTypeValue_check]
        param[1] = ['订单流水号', this.orderNumberTypeValue]
        param[2] = ['组件流水号_check', productNameValue_check]
        param[3] = ['组件流水号', this.productNameValue]
        param[4] = ['采购状态_check', purchasingStatusValue_check]
        param[5] = ['采购状态', this.purchasingStatusValue]
        param[6] = ['采购件_check', purchasePartValue_check]
        param[7] = ['采购件', this.purchasePartValue]
        param[8] = ['图号_check', purchaseModel_check]
        param[9] = ['图号', this.purchaseModel]
        param[10] = ['时间_check', dateRange_check]
        param[11] = ['开始时间', this.dateRange[0]]
        param[12] = ['结束时间', this.dateRange[1]]
        param[13] = ['排序名称', this.orderName]
        param[14] = ['排序方式', this.order]
        var Data = this.CreateData('2001', '采购管理_采购件_查询数据_导出用', param)
        this.exportExcel_NPOI(Data)
      } else {
        this.$message.warning('暂无数据')
      }
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (index === 4) {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index]
          } else {
            sums[index] = 'N/A'
          }
        } else if (index === 5) {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(2)
          } else {
            sums[index] = 'N/A'
          }
        } else if (index === 8) {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index]
          } else {
            sums[index] = 'N/A'
          }
        }
      })
      return sums
    },
    repealOk(row) {
      this.$confirm('是否撤回此手动完成采购记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['id', row.id]
        param[1] = ['修改人', this.id]
        var Data = this.CreateData('12', '采购管理_手动完成记录_撤回', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('撤回成功')
            this.searchTable()
            this.viewModifyPurchaseClick()
          } else {
            this.$message.error('撤回失败')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    sortChange(column) {
      if (column.prop === '采购件') {
        this.orderName = 1
      } else if (column.prop === '交货日期') {
        this.orderName = 2
      } else if (column.prop === '任务下达 ') {
        this.orderName = 3
      } else if (column.prop === '采购日期 ') {
        this.orderName = 4
      } else {
        this.orderName = 0
      }
      if (column.order === 'ascending') {
        this.order = 1
      } else if (column.order === 'descending') {
        this.order = 2
      } else {
        this.order = ''
      }
      this.searchTable()
    },
    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.searchTable()
    }
  }
}
</script>

