<template>
  <div class="app-container">
    <el-card>
      <div slot="header">
        <!--<span>供应商：</span>-->
        <el-select v-model="supplierValue" placeholder="供应商" filterable size="small" style="margin-left: 5px" clearable @change="totalSum=0;totalPay=0;totalDebt=0;">
          <el-option
            v-for="item in supplier"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <span>请款时间：</span>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          size="small"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="~"
          style="width:240px;margin-left: 10px"
          start-placeholder="开始日期"
          end-placeholder="结束日期"/>
        <el-button type="primary" size="small" icon="el-icon-search" plain style="margin-left: 10px" @click="pageCurrent1=1;pageSize1=10;total1=0;searchTable1()">查询</el-button>
        <el-button type="warning" size="small" icon="el-icon-goods" plain style="" @click="requestFund">请款</el-button>
        <!--        <el-checkbox v-model="searchAll" style="margin-left: 50px">查询全部</el-checkbox>-->
        <el-button type="success" size="small" icon="el-icon-download" plain style="float: right; margin-right: 20px;" @click="exportExcel">导出</el-button>
      </div>
      <!--<h3>请款表</h3>-->
      <el-table v-loading="" :data="tableData1" border size="mini" height="200" stripe highlight-current-row @row-click="searchTable02">
        <el-table-column label="供应商" prop="供应商名称" align="center" width="220" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.供应商名称 }}
          </template>
        </el-table-column>
        <el-table-column label="请款人" prop="姓名" align="center" min-width="70" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.姓名 }}
          </template>
        </el-table-column>
        <el-table-column label="请款金额（元）" align="center" width="150" prop="请款金额">
          <template slot-scope="scope">
            {{ scope.row.请款金额 }}
          </template>
        </el-table-column>
        <el-table-column label="请款时间" prop="请款时间" align="center" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.请款时间 ? scope.row.请款时间.split(' ')[0] : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="审核结果" width="80" align="center">
          <template slot-scope="scope">
            <el-tag v-if="Number(scope.row.审核情况流水号)===3" type="primary" size="small">未审</el-tag>
            <el-tag v-if="Number(scope.row.审核情况流水号)===1" type="success" size="small">通过</el-tag>
            <el-tag v-if="Number(scope.row.审核情况流水号)===2" type="danger" size="small">未过</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核未过原因" width="110" align="center">
          <template slot-scope="scope">
            {{ scope.row.未通过审核原因 === '通过' ? '—' : scope.row.未通过审核原因 }}
          </template>
        </el-table-column>
        <el-table-column label="审批结果" width="80" align="center">
          <template slot-scope="scope">
            <el-tag v-if="Number(scope.row.审批情况流水号)===3" type="primary" size="small">未审</el-tag>
            <el-tag v-if="Number(scope.row.审批情况流水号)===1" type="success" size="small">通过</el-tag>
            <el-tag v-if="Number(scope.row.审批情况流水号)===2" type="danger" size="small">未过</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审批未过原因" width="110" align="center">
          <template slot-scope="scope">
            {{ scope.row.未通过审批原因 === '通过' ? '—' : scope.row.未通过审批原因 }}
          </template>
        </el-table-column>
        <el-table-column label="付款结果" width="80" align="center">
          <template slot-scope="scope">
            <el-tag v-if="Number(scope.row.付款情况流水号)===3" type="primary" size="small">未付</el-tag>
            <el-tag v-if="Number(scope.row.付款情况流水号)===1" type="success" size="small">已付</el-tag>
            <el-tag v-if="Number(scope.row.付款情况流水号)===2" type="danger" size="small">不同意</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="未付原因" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.未付款原因 === '通过' ? '—' : scope.row.未付款原因 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-tooltip v-show="true" :open-delay="100" content="删除请款信息" placement="right">
              <el-button :disabled="Number(id)!==Number(scope.row.请款人) || !((Number(scope.row.审核情况流水号) !== 1) || (Number(scope.row.审批情况流水号)===2) || (Number(scope.row.付款情况流水号)===2))" type="text" size="mini" icon="el-icon-delete" style="margin-left: 10px" @click="cancelRequestFund(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin-top: 10px;">
        <el-pagination
          :current-page="pageCurrent1"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize1"
          :total="total1"
          style="display:inline-block;width:700px"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange1"
          @current-change="handleCurrentChange1"/>
      </div>
    </el-card>
    <el-card>
      <!--<h3 style="margin-top: 0">合同明细</h3>-->
      <el-row>
        <el-col :span="10">
          <el-card>
            <el-table :data="gridData" :summary-method="getSummaries2" border highlight-current-row size="mini" show-summary @row-click="searchContract">
              <el-table-column width="100" align="center" label="合同编号">
                <template slot-scope="scope">
                  {{ scope.row.采购合同编号 ? scope.row.采购合同编号 : scope.row.离线合同编号 }}
                </template>
              </el-table-column>
              <el-table-column width="110" align="center" label="合同总额(元)" prop="合同总额">
                <template slot-scope="scope">
                  <span v-if="scope.row.合同总额">{{ scope.row.合同总额 ? parseFloat(scope.row.合同总额).toFixed(2) : 0 }}</span>
                  <span v-if="scope.row.离线合同总额">{{ scope.row.离线合同总额 ? parseFloat(scope.row.离线合同总额).toFixed(2) : 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column width="110" align="center" label="到货金额(元)" prop="到货金额">
                <template slot-scope="scope">
                  {{ parseFloat(scope.row.到货金额).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column width="110" align="center" label="已付金额(元)" prop="已付金额">
                <template slot-scope="scope">
                  {{ parseFloat(scope.row.已付金额).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column width="110" align="center" label="请款金额(元)" prop="请款金额">
                <template slot-scope="scope">
                  {{ parseFloat(scope.row.请款金额).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="14">
          <el-card>
            <el-table :data="tableData2" :summary-method="getSummaries" border height="450px" size="mini" stripe show-summary>
              <el-table-column label="物料名称" align="center" min-width="120">
                <template slot-scope="scope">
                  {{ scope.row.物料名称 ? scope.row.物料名称 : scope.row.零件名称 }}
                </template>
              </el-table-column>
              <el-table-column label="物料规格" align="center" min-width="130" show-overflow-tooltip>
                <template slot-scope="scope">
                  {{ scope.row.物料规格 ? scope.row.物料规格 : scope.row.规格 }}
                </template>
              </el-table-column>
              <el-table-column label="物料型号" align="center" width="130" show-overflow-tooltip>
                <template slot-scope="scope">
                  {{ scope.row.物料型号 ? scope.row.物料型号 : scope.row.零件图号 }}
                </template>
              </el-table-column>
              <el-table-column label="采购数量" align="center" width="80">
                <template slot-scope="scope">
                  {{ scope.row.数量 }}
                </template>
              </el-table-column>
              <el-table-column label="到货数量" align="center" width="80">
                <template slot-scope="scope">
                  {{ scope.row.合同类型 === 1 ? scope.row.已到货数量 : scope.row.到货数量 }}
                </template>
              </el-table-column>
              <!--<el-table-column label="合计" align="center" min-width="100" prop="合计">-->
              <!--<template slot-scope="scope">-->
              <!--{{ (parseFloat(scope.row.单价||0) * parseInt(scope.row.数量||0)).toFixed(2) }}-->
              <!--</template>-->
              <!--</el-table-column>-->
              <!--<el-table-column label="单价" align="center" min-width="100" prop="单价">-->
              <!--<template slot-scope="scope">-->
              <!--{{ parseFloat(scope.row.单价||0).toFixed(2) }}-->
              <!--</template>-->
              <!--</el-table-column>-->
              <el-table-column label="交货期要求" align="center" min-width="100" prop="交货期要求">
                <template slot-scope="scope">
                  {{ scope.row.合同类型 === 1 ? scope.row.交货期.split(' ')[0] === '1900-01-01' ? '-' : scope.row.交货期.split(' ')[0] : scope.row.交货期要求 }}
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" min-width="120" prop="备注">
                <template slot-scope="scope">
                  {{ scope.row.备注 }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog v-el-drag-dialog :visible.sync="dialogVisible2" title="采购合同请款" center style="min-height: 300px" width="1000px">
      <span>供应商：</span>
      <el-select v-model="supplierValue" placeholder="供应商" filterable clearable size="small" @change="searchTable01()">
        <el-option
          v-for="item in supplier"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      <!--<el-button type="success" size="small" icon="el-icon-search" style="margin: 0 10px 10px 10px" @click="searchTable01()">查询</el-button>-->
      <el-table v-loading="" :data="tableData01" border style="max-height: 300px;" height="300px" size="mini" @selection-change="handleSelectionChange">
        <el-table-column :selectable="selectable" type="selection" align="center" width="45"/>
        <el-table-column label="采购合同编号" align="center" width="130" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.采购合同编号 }}
          </template>
        </el-table-column>
        <el-table-column label="采购合同名称" align="center" min-width="110" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.采购合同名称 }}
          </template>
        </el-table-column>
        <el-table-column label="采购员" align="center" width="70">
          <template slot-scope="scope">
            {{ scope.row.姓名 }}
          </template>
        </el-table-column>
        <el-table-column label="合同类型" align="center" width="80">
          <template slot-scope="scope">
            {{ scope.row.合同类型 === 1 ? '采购' : '离线' }}
          </template>
        </el-table-column>
        <el-table-column label="合同总额(元)" align="center" width="110" prop="合同总额">
          <template slot-scope="scope">
            {{ scope.row.合同总额 ? (parseInt(scope.row.合同总额 * 100)/100).toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="已付金额(元)" align="center" width="110" prop="已付金额">
          <template slot-scope="scope">
            {{ parseFloat(scope.row.已付金额).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="申请中金额(元)" align="center" min-width="120" prop="申请中金额">
          <template slot-scope="scope">
            {{ parseFloat(scope.row.申请中金额).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="请款金额(元)" align="center" min-width="170" prop="请款金额">
          <template slot-scope="scope">
            <el-input-number :max="scope.row.合同总额 - scope.row.已付金额 - scope.row.申请中金额" :disabled="(scope.row.合同总额 - scope.row.已付金额 - scope.row.申请中金额) === 0" :min="0" v-model="scope.row.请款金额" :precision="2" size="mini" controls-position="right" style="width: 100%;"/>
          </template>
        </el-table-column>
      </el-table>
      <span>合计：<el-input v-model="SUM" readonly size="mini" style="width: 150px; margin: 10px 10px 0 10px"/>元</span>
      <el-button type="primary" size="small" style="float:right;margin: 10px" icon="el-icon-check" @click="submitRequestFund">确定请款</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { searchTable0, searchContract, searchSupplier, searchRequestFund, searchPurchaseContract, submitRequestFund, searchRequsetFundDetail, cancelRequestFund } from '@/api/PurchasingCenter/PurchaseContractRequestFund'
import { mapGetters } from 'vuex'
import { getNowTime, timeToStamp } from '@/utils/tool'

export default {
  data() {
    return {
      searchAll: true,
      selectContents: [],
      getDate: null,
      tableData0: [],
      pickerOptions: {
        shortcuts: [{
          text: '未来一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '未来一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '未来两个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30 * 2)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '未来三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '未来半年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30 * 6)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      dateRange: '',
      tableData1: [],
      total1: 0,
      pageCurrent1: 1,
      pageSize1: 10,
      returns: '',
      supplierValue: '',
      supplier: [],
      totalSum: 0,
      totalPay: 0,
      totalDebt: 0,
      tableData2: [],
      dialogVisible2: false,
      tableData01: [],
      SUM: 0,
      contractGroup: [],
      offGroup: [],
      gridData: []
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'name',
      'id'
    ])
  },
  created() {
    this.fetchData()
    // this.searchTable0()
    // this.searchTable1()
  },
  methods: {
    exportExcel() { // 合同请款导出
      let check1, check2
      this.dateRange ? check1 = 1 : (check1 = 0, this.dateRange = '')
      this.supplierValue ? check2 = 1 : check2 = 0
      var param = []
      param[0] = ['时间段_check', check1]
      param[1] = ['开始时间', this.dateRange[0]]
      param[2] = ['结束时间', this.dateRange[1]]
      param[3] = ['供应商流水号_check', check2]
      param[4] = ['供应商流水号', this.supplierValue]
      console.log(param, 'param')
      var Data = this.CreateData('2001', '报表_合同请款', param)
      this.exportExcel_NPOI(Data)
    },
    timeToStamp(param) { // 转时间戳
      return timeToStamp(param)
    },
    searchTable0() { // 查询付款计划
      this.getDate = timeToStamp(getNowTime()) // 获取当前时间
      let check
      this.dateRange ? check = 1 : (check = 0, this.dateRange = '')
      searchTable0(check, this.dateRange[0], this.dateRange[1]).then(response => {
        this.tableData0 = response.data
      })
    },
    fetchData() {
      this.supplier = []
      searchSupplier().then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.supplier.push({
            label: response.data[i].供应商名称,
            value: response.data[i].供应商流水号
          })
        }
      })
    },
    searchContract(row) {
      var check
      row.采购合同流水号 ? check = 1 : check = 2
      searchContract(check, row.采购合同流水号, row.离线合同流水号).then(response => {
        this.tableData2 = response.data
      })
    },
    getSummaries(param) { // 合计
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 3) {
          const values = data.map(item => Number(parseFloat(item['数量'])))
          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] = '0'
          }
        } else if (index === 4) {
          for (let i = 0; i < data.length; i++) {
            if (!data[i].到货数量) {
              data[i].到货数量 = 0
            }
            if (!data[i].已到货数量) {
              data[i].已到货数量 = 0
            }
          }
          const values = data.map(item => Number(parseInt(item['到货数量'])) + Number(parseInt(item['已到货数量'])))
          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] = '0'
          }
        }
      })
      return sums
    },
    getSummaries2(param) { // 合计
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价'
          return
        } else if (index === 2 || index === 3 || index === 1) {
          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'
          }
        }
      })
      return sums
    },
    handleSizeChange1(val) {
      this.pageSize1 = val
      this.pageCurrent1 = 1
      this.searchTable1()
    },
    handleCurrentChange1(val) {
      this.pageCurrent1 = val
      this.searchTable1()
    },
    searchTable1() { // 查请款信息
      let check1, check2, check3
      this.dateRange ? check1 = 1 : (check1 = 0, this.dateRange = '')
      this.supplierValue ? check2 = 1 : check2 = 0
      this.searchAll === false ? check3 = 1 : check3 = 0
      searchRequestFund(this.pageCurrent1, this.pageSize1, check1, this.dateRange[0], this.dateRange[1], check2, this.supplierValue, check3).then(response => {
        this.tableData1 = response.data.rows
        this.total1 = response.data.total
      })
      this.totalSum = 0
      this.totalPay = 0
      searchPurchaseContract(1, check2, this.supplierValue).then(response => {
        response.data.map(data => {
          this.totalSum += data.合同总额
          this.totalPay += data.已付金额
        })
        this.totalDebt = this.totalSum - this.totalPay
      })
    },
    requestFund() { // 请款
      this.dialogVisible2 = true
      this.supplierValue = ''
      this.fetchData() // 重新获取供应商
      this.tableData01 = []
    },
    searchTable01() { // 查询待请款
      if (this.supplierValue) {
        this.contractGroup = []
        this.offGroup = []
        let check
        this.supplierValue ? check = 1 : check = 0
        searchPurchaseContract(2, check, this.supplierValue).then(response => {
          this.tableData01 = response.data
          this.tableData01.map(v => {
            this.$set(v, '请款金额', 0)
            v.请款金额 = v.合同总额 - v.已付金额 - v.申请中金额
            return v
          })
        })
      }
    },
    selectable(row, index) { // 控制某行是否可选
      return parseInt(row.已请款) !== 1 // 已经请款
    },
    handleSelectionChange(val) {
      this.selectContents = val
      this.SUM = 0
      this.contractGroup = []
      this.offGroup = []
      this.sumGroup = []
      for (let i = 0; i < val.length; i++) {
        this.SUM += parseFloat(val[i].请款金额)
        this.contractGroup.push(val[i].采购合同流水号)
        this.offGroup.push(val[i].采购合同流水号)
        this.sumGroup.push(val[i].请款金额)
      }
      this.SUM = parseFloat(this.SUM).toFixed(2)
    },
    submitRequestFund() { // 确认请款
      if (this.supplierValue && this.contractGroup.length !== 0) {
        this.SUM = 0
        this.contractGroup = []
        this.offGroup = []
        this.sumGroup = []
        for (let i = 0; i < this.tableData01.length; i++) {
          for (let j = 0; j < this.selectContents.length; j++) {
            if (this.selectContents[j].采购合同流水号 === this.tableData01[i].采购合同流水号 && this.selectContents[j].合同类型 === this.tableData01[i].合同类型) {
              if (this.selectContents[j].合同类型 === 1) {
                this.SUM += parseFloat(this.tableData01[i].请款金额)
                this.contractGroup.push(this.tableData01[i].采购合同流水号)
                this.offGroup.push('a974548')
                this.sumGroup.push(this.tableData01[i].请款金额)
              } else {
                this.SUM += parseFloat(this.tableData01[i].请款金额)
                this.contractGroup.push('a974548')
                this.offGroup.push(this.tableData01[i].采购合同流水号)
                this.sumGroup.push(this.tableData01[i].请款金额)
              }
            }
          }
        }
        if (this.SUM === 0) {
          this.$message.error('请款金额不能为0')
        } else {
          submitRequestFund(this.contractGroup, this.offGroup, this.sumGroup, this.supplierValue, this.SUM, this.id).then(response => {
            if (response.data[0].result === '1') {
              this.$message.success('请款成功')
              this.searchTable1()
              this.dialogVisible2 = false
            } else {
              this.$message.error('请款失败')
            }
          })
        }
      } else {
        this.$message.error('请选择需要请款的合同')
      }
    },
    searchTable02(row) { // 查看详情（请款信息包含的合同）
      searchRequsetFundDetail(row.采购合同请款流水号).then(response => {
        this.gridData = response.data
      })
    },
    cancelRequestFund(row) { // 取消请款
      this.$confirm('确定取消请款?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelRequestFund(row.采购合同请款流水号).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('操作成功')
            this.searchTable1()
          } else if (response.data[0].result === '已审批') {
            this.searchTable1()
            this.$message.error('已审批,操作失败')
          } else { this.$message.error('操作失败') }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    }
  }
}
</script>

<style scoped>
  .el-tag{
    margin: 0
  }
  .el-card{
    margin-bottom: 0px;
  }
  .el-date-editor{
    width:150px;
  }
  .el-select{
    width:200px
  }
  .el-input{
    width:200px
  }
  span{
    margin: 10px 0 10px 10px;
  }
  .searchForm .el-form-item{
    margin-bottom: 5px;
  }
</style>
