<template>
  <div class="app-container">
    <el-card>
      <span>时间段:</span>
      <el-date-picker
        v-model="dateRange"
        :picker-options="pickerOptions"
        size="small"
        type="daterange"
        align="center"
        value-format="yyyy-MM-dd"
        format="yyyy-MM-dd"
        range-separator="～"
        style="width:300px"
        start-placeholder="开始日期"
        end-placeholder="结束日期"/>
      <span>供应商：</span>
      <el-select v-model="supplierValue" placeholder="供应商" filterable size="small" 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>
      <el-button
        type="success"
        size="small"
        icon="el-icon-search"
        style="margin-left: 10px"
        @click="pageCurrent1=1;pageSize1=10;total1=0;searchTable1()">查询</el-button>
      <el-button type="primary" size="small" icon="el-icon-goods" style="" @click="requestFund">请款</el-button>
    </el-card>

    <el-card>
      <el-table v-loading="" :data="tableData1" border style="max-height: 500px;" height="500px" size="mini">
        <el-table-column label="供应商" align="center" min-width="250">
          <template slot-scope="scope">
            {{ scope.row.供应商名称 }}
          </template>
        </el-table-column>
        <el-table-column label="请款时间" align="center" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.请款时间 }}
          </template>
        </el-table-column>
        <el-table-column label="请款人" align="center" min-width="80">
          <template slot-scope="scope">
            {{ scope.row.姓名 }}
          </template>
        </el-table-column>
        <el-table-column label="请款金额" align="center" min-width="90" prop="请款金额">
          <template slot-scope="scope">
            {{ scope.row.请款金额 }}
          </template>
        </el-table-column>
        <el-table-column label="请款付款情况" align="center">
          <el-table-column label="审批情况内容" width="100" 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="100" 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>
        <el-table-column label="操作" align="center" width="250">
          <template slot-scope="scope">
            <el-popover placement="right" width="500" trigger="click">
              <el-table :data="gridData" highlight-current-row size="mini" show-summary>
                <el-table-column width="50" align="center" type="index" label="序号"/>
                <el-table-column min-width="150" align="center" label="采购合同编号">
                  <template slot-scope="scope">
                    {{ scope.row.采购合同编号 }}
                  </template>
                </el-table-column>
                <el-table-column min-width="100" align="center" label="已付金额" prop="已付金额">
                  <template slot-scope="scope">
                    {{ scope.row.已付金额 }}
                  </template>
                </el-table-column>
                <el-table-column min-width="100" align="center" label="请款金额" prop="请款金额">
                  <template slot-scope="scope">
                    {{ scope.row.请款金额 }}
                  </template>
                </el-table-column>
              </el-table>
              <el-button slot="reference" type="success" size="mini" icon="el-icon-search" @click="searchTable02(scope.row)">查看详情</el-button>
            </el-popover>
            <el-button :disabled="Number(scope.row.审批情况流水号)!==3" type="danger" size="mini" icon="el-icon-delete" style="margin-left: 10px" @click="cancelRequestFund(scope.row)">取消请款</el-button>
          </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:50%"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange1"
          @current-change="handleCurrentChange1"/>
        <span v-show="supplierValue">累计合同总额：</span>
        <el-input v-show="supplierValue" v-model="totalSum" size="mini" style="width: 100px;" readonly/>
        <span v-show="supplierValue">累计付款：</span>
        <el-input v-show="supplierValue" v-model="totalPay" size="mini" style="width: 100px;" readonly/>
        <span v-show="supplierValue">累计欠款：</span>
        <el-input v-show="supplierValue" v-model="totalDebt" size="mini" style="width: 100px;" readonly/>
      </div>
    </el-card>

    <el-dialog :visible.sync="dialogVisible2" title="采购合同请款" center style="min-height: 300px" width="1200px">
      <span>供应商：</span>
      <el-select v-model="supplierValue" placeholder="供应商" filterable clearable size="small">
        <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="50"/>
        <el-table-column label="采购合同编号" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.采购合同编号 }}
          </template>
        </el-table-column>
        <el-table-column label="采购合同名称" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.采购合同名称 }}
          </template>
        </el-table-column>
        <el-table-column label="供应商" align="center" min-width="180">
          <template slot-scope="scope">
            {{ 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="100" prop="合同总额">
          <template slot-scope="scope">
            {{ scope.row.含税总金额 }}
          </template>
        </el-table-column>
        <el-table-column label="已付金额" align="center" min-width="100" prop="已付金额">
          <template slot-scope="scope">
            {{ scope.row.已付金额 }}
          </template>
        </el-table-column>
        <el-table-column label="请款金额" align="center" min-width="100" prop="请款金额">
          <template slot-scope="scope">
            <el-input-number :max="scope.row.含税总金额 - scope.row.已付金额" :disabled="(scope.row.含税总金额 - scope.row.已付金额) === 0" v-model="scope.row.请款金额" controls-position="right" size="mini" style="width: 100%;"/>
          </template>
        </el-table-column>
      </el-table>
      <span>合计：<el-input v-model="SUM" readonly size="mini" style="width: 80px; 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 { searchSupplier, searchRequestFund, searchPurchaseContract, submitRequestFund, searchRequsetFundDetail, cancelRequestFund } from '@/api/WorkshopProcurement/PurchaseContractRequestFund1'
import { mapGetters } from 'vuex'
import { timeToStamp } from '@/utils/tool'

export default {
  data() {
    return {
      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: [],
      gridData: []
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'name',
      'id'
    ])
  },
  created() {
    this.fetchData()
    this.searchTable1()
  },
  methods: {
    timeToStamp(param) { // 转时间戳
      return timeToStamp(param)
    },
    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].供应商流水号
          })
        }
      })
    },
    handleSizeChange1(val) {
      this.pageSize1 = val
      this.pageCurrent1 = 1
      this.searchTable1()
    },
    handleCurrentChange1(val) {
      this.pageCurrent1 = val
      this.searchTable1()
    },
    searchTable1() { // 查请款信息
      let check1, check2
      this.dateRange ? check1 = 1 : (check1 = 0, this.dateRange = '')
      this.supplierValue ? check2 = 1 : check2 = 0
      searchRequestFund(this.pageCurrent1, this.pageSize1, check1, this.dateRange[0], this.dateRange[1], check2, this.supplierValue).then(response => {
        this.tableData1 = response.data.rows
        this.total1 = response.data.total
      })
      this.totalSum = 0
      this.totalPay = 0
      searchPurchaseContract(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 = []
        let check
        this.supplierValue ? check = 1 : check = 0
        searchPurchaseContract(check, this.supplierValue).then(response => {
          this.tableData01 = response.data
          this.tableData01.map(v => {
            this.$set(v, '请款金额', 0)
            v.请款金额 = v.含税总金额 - v.已付金额
            return v
          })
        })
      } else {
        this.$message.error('请选择供应商')
      }
    },
    selectable(row, index) { // 控制某行是否可选
      return parseInt(row.已请款) !== 1 // 已经请款
    },
    handleSelectionChange(val) {
      this.SUM = 0
      this.contractGroup = []
      this.sumGroup = []
      for (let i = 0; i < val.length; i++) {
        this.SUM += parseFloat(val[i].请款金额)
        this.contractGroup.push(val[i].采购合同流水号)
        this.sumGroup.push(val[i].请款金额)
      }
    },
    submitRequestFund() { // 确认请款
      if (this.supplierValue && this.contractGroup.length !== 0) {
        submitRequestFund(this.contractGroup, 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: 15px;
  }
  .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>
