<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom: 10px">
      <el-input size="mini" v-model="search.keyWord" placeholder="关键字" style="width: 130px;" class="filter-item"/>
      <el-input size="mini" v-model="search.orderCode" placeholder="订单编号" style="width: 130px;" class="filter-item" />
      <el-input size="mini" v-model="search.applyMan" placeholder="认款申请提交人" style="width: 130px;" class="filter-item" />
      <el-input size="mini" v-model="search.guarantorPerson" placeholder="担保人" style="width: 130px;" class="filter-item" />
      <el-date-picker
        size="mini"
        v-model="searchTime"
        type="daterange"
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd">
      </el-date-picker>
      <el-select size="mini" v-model="search.applyFlag">
        <el-option label="全部" value="1,2"></el-option>
        <el-option label="待确认" value="1"></el-option>
        <el-option label="已确认" value="2"></el-option>
      </el-select>
      <el-checkbox size="mini" @change="checkLock" v-model="LockBtn" label="只查欠款" border></el-checkbox>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="batchBtn">
        批量审核
      </el-button>

      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getListInfo"/>
        </el-tooltip>
      </div>
    </div>
    <el-table
      :data="tableData"
      v-loading="listLoading"
      @selection-change="handleSelectionChangeBatch"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      size="mini"
      border
      default-expand-all>
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        fixed
        width="200"
        align="center"
        label="操作">
        <template slot-scope="{row}">
          <el-button
            v-if="row.applyFlag != 2"
            @click.stop="backBtn(row)"
            size="mini"
            type="warning">
            退回
          </el-button>
          <el-button
            v-if="row.applyFlag != 2"
            @click.stop="handleForBtn(row)"
            size="mini"
            type="primary">
            认款确认
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="guarantorPerson"
        label="担保人">
      </el-table-column>
      <el-table-column
        width="140"
        prop="applyFlag"
        label="认款申请状态">
        <template slot-scope="{row}">
          <el-tag v-if="row.applyFlag == 1" type="warning">待财务确认</el-tag>
          <el-tag v-else-if="row.applyFlag == 2" type="success">财务确认完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column
      prop="applyMemo"
      width="180"
      show-overflow-tooltip
      label="认款说明">
    </el-table-column>
      <el-table-column
        prop="applyMan"
        width="120"
        show-overflow-tooltip
        label="提交人">
      </el-table-column>
<!--      <el-table-column-->
<!--        prop="guarantorCheckFlag"-->
<!--        label="审核状态">-->
<!--        <template slot-scope="{row}">-->
<!--          <el-tag v-if="row.guarantorCheckFlag == 0" type="warning">未审核</el-tag>-->
<!--          <el-tag v-else-if="row.guarantorCheckFlag == 1" type="success">已审核</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column
        prop="orderCode"
        width="100"
        label="订单编码">
        <template slot-scope="{row}">
          <a href="javascript:;" style="color: #20a0ff" @click="getOrderStep(row)">{{ row.orderCode }}</a>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderName"
        width="100"
        show-overflow-tooltip
        label="订单名称">
        <template slot-scope="{row}">
          <a href="javascript:;" style="color: #20a0ff" @click="openDetail(row.idOrder)">{{ row.orderName }}</a>
        </template>
      </el-table-column>
      <el-table-column
        prop="clientName"
        width="100"
        show-overflow-tooltip
        label="客户名称">
      </el-table-column>
      <el-table-column
        prop="orderMoneyTotal"
        label="订单金额">
      </el-table-column>
      <el-table-column
        prop="chargeMoney"
        label="应收金额">
      </el-table-column>
      <el-table-column
        prop="guarantorMoney"
        label="担保金额">
      </el-table-column>
      <el-table-column
        prop="orderCreateTime"
        label="制单日期"
        width="160">
        <template slot-scope="{row}">
          <span v-if="row.orderCreateTime"> {{ row.orderCreateTime | getTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderCreateMan"
        label="制单人">
      </el-table-column>
      <el-table-column
        prop="feedBackDate"
        label="发货反馈时间"
        width="160">
        <template slot-scope="{row}">
          <span v-if="row.feedBackDate"> {{ row.feedBackDate | getTime }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column-->
      <!--        prop="actSendDate"-->
      <!--        label="订单交货日期"-->
      <!--        width="160">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span v-if="row.actSendDate"> {{ row.actSendDate | getTime }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column
        prop="orderMemo"
        show-overflow-tooltip
        label="订单备注">
      </el-table-column>
    </el-table>
    <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page"
                :limit.sync="listData.pageSize" @pagination="getListInfo"/>
    <order-step ref="orderStep"></order-step>
    <el-dialog title="订单详情" :close-on-click-modal="false" class="orderDetailDialog" :visible.sync="detailVisible"
               top="10px" width="1200px">
      <order-detail ref="orderDetail"></order-detail>
    </el-dialog>
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
    <el-dialog width="800px" title="认款确认" :visible.sync="dialogTableVisible">
      <el-form label-width="70px" size="mini">
        <el-col :span="24">
          <el-form-item label="认款说明" label-width="70px">
            <span>{{applyMemo}}</span>
          </el-form-item>
        </el-col>
        <el-row :gutter="20">
<!--          <el-col :span="12">-->
<!--            <el-form-item label="收款时间">-->
<!--              <el-date-picker-->
<!--                style="width: 230px"-->
<!--                v-model="multiChargeData.chargeDate"-->
<!--                type="datetime"-->
<!--                value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                placeholder="选择日期">-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="交款人" label-width="70px">-->
<!--              <el-input-->
<!--                style="width: 230px"-->
<!--                v-model="multiChargeData.payMan"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="会计科目" label-width="70px">-->
<!--              <el-select-->
<!--                v-model="multiChargeData.idAccount"-->
<!--                filterable-->
<!--                style="width: 230px">-->
<!--                <el-option-->
<!--                  v-for=" item in accountInfo"-->
<!--                  :key="item.id"-->
<!--                  :value="item.id"-->
<!--                  :label="item.accountCode+item.accountName">-->
<!--                  <span style="float: left">{{ item.accountName }}</span>-->
<!--                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.accountCode }}</span>-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="凭证号" label-width="70px">-->
<!--              <el-input-->
<!--                v-model="multiChargeData.voucherCode"-->
<!--                style="width: 230px"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="收款金额" label-width="70px">-->
<!--              <el-input-->
<!--                type="number"-->
<!--                v-model="amountMoney"-->
<!--                style="width: 210px"></el-input>-->
<!--              <el-button size="mini" @click="distribute">金额分配</el-button>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="收款方式">-->
<!--              <el-radio-group  v-model="multiChargeData.chargeKind">-->
<!--                <el-radio :label="0">金额</el-radio>-->
<!--                <el-radio :label="1">物流代收</el-radio>-->
<!--              </el-radio-group>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
            <el-table :data="gridData" :show-summary="true" border size="mini">
              <el-table-column show-overflow-tooltip width="140" label="订单名称" prop="orderName"></el-table-column>
              <el-table-column label="订单编号" prop="orderCode"></el-table-column>
              <el-table-column label="客户名称" prop="clientName"></el-table-column>
              <!--              <el-table-column label="物流货号" prop="orderName"></el-table-column>-->
              <el-table-column label="应收" prop="chargeMoney"></el-table-column>
<!--              <el-table-column label="当前收款" prop="receivableMoney">-->
<!--                <template slot-scope="{row}">-->
<!--                  <sapn>{{row.receivableMoney}}</sapn>-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column label="折扣" prop="agioMoney">-->
<!--                <template slot-scope="{row}">-->
<!--                  <span>{{row.agioMoney}}</span>-->
<!--                </template>-->
<!--              </el-table-column>-->
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button :disabled="disabledBtn" type="primary" @click="confirmBtn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  orderGuarantorInfoReviewPage,
  guarantorAccountApplyCancel,
  getOrderGuarantorInfo,
  getOrderReceivableByOrder,
  guarantorAccountApplyConfirm,
  guarantorAccountApplyConfirmBatch
} from '@/api/financial/guarantorReview'
import {
  getAccountInfoList
} from '@/api/orderCharge/orderCollection'
import OrderStep from "@/components/orderStep/orderStep";
import OrderDetail from "@/components/orderDetail/orderDetail";
import Cancledialog from "@/components/Dialog/Cancledialog";

export default {
  name: 'subscription',
  components: {Cancledialog, OrderDetail, OrderStep},
  props: {
    isChoose: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      disabledBtn:false,
      amountMoney: 0, // 收款金额
      accountInfo: [], // 科目
      multiChargeData:{
        chargeDate: new Date(),
        payMan: '',
        idAccount: '',
        voucherCode: '',
        chargeKind: 0
      },
      idRow:"",
      applyMemo:"",
      dialogTableVisible:false,
      gridData:[],
      webType: true,
      search: {
        keyWord: '',
        applyFlag: '1',
        applyBeginTime:"",
        applyEndTime:"",
        applyMan:"",
        orderCode:"",
        guarantorPerson:"",
        onlyCharge:1,
      },
      LockBtn: true,
      searchTime: [],
      form: {},
      options: [],

      listData: {
        total: 0,
        page: 1,
        pageSize: 20
      },

      listLoading: false,
      multipleSelection:[],
      multipleSelectionBatch:[],
      tableData: [],
      chooseList: [],
      backDialog: false,
      backInfo: {
        id: '',
        guarantorReturnMemo: ''
      },

      detailVisible: false

    }
  },
  mounted() {
    // this.search.guarantorPerson = this.$store.state.user.name
    this.getListInfo()
    this.getAccountInfo()
  },
  methods: {
    checkLock(val){
      const _that = this;
      console.log(val);
      if (_that.LockBtn) {
        _that.search.onlyCharge = 1
      }else {
        _that.search.onlyCharge = 0
      }
    },
    batchBtn(){
      const _that = this;
      if (_that.multipleSelectionBatch.length <= 0) {
        _that.$message("请选择订单");
        return
      }
      _that.$confirm('确认批量审核？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        var ids = [];
        for (var i = 0; i < _that.multipleSelectionBatch.length; i++) {
          var datas = _that.multipleSelectionBatch[i];
          ids.push(datas.id);
        }
        var data = {
          'ids': ids
        }
        guarantorAccountApplyConfirmBatch(data).then(res => {
          // console.log(res);
          if (res.httpCode == 200) {
            _that.$message.success("批量确认成功");
            _that.listData.page = 1;
            _that.getListInfo();
          } else {
          }
        }).catch(err => {
        })
      }).catch(() => {

      })

    },
     confirmBtn(){
      //确定
      const _that = this;
       _that.idRow

      // if(!_that.multiChargeData.idAccount){
      //   _that.$message.warning('请输入会计科目')
      //   return;
      // }
      // for (let i = 0; i < _that.gridData.length; i++) {
      //   var item = _that.gridData[i]
      //   Object.assign(item, _that.multiChargeData)
      //   // console.log(item)
      //   if (item.receivableMoney == 0 && item.agioMoney == 0) {
      //     _that.gridData.splice(i, 1)
      //     i--
      //   }
      //   if (parseFloat(item.receivableMoney) + parseFloat(item.agioMoney) > item.chargeMoney) {
      //     _that.$message.error('收款金额与折扣之和不得大于应收金额')
      //     return
      //   }
      // }
      _that.disabledBtn = true;
      // var rowData = []
      // _that.gridData.forEach(row => {
      //   var rows = {
      //     idReceivable: row.idReceivable,
      //     idAccount: row.idAccount,
      //     chargeDate: _that.multiChargeData.chargeDate,
      //     payMan: row.payMan,
      //     chargeKind: row.chargeKind,
      //     idOrder: row.idOrder,
      //     orderCode: row.orderCode,
      //     receivableMoney: row.receivableMoney,
      //     agioMoney: row.agioMoney,
      //     voucherCode: row.voucherCode,
      //     versionCode: row.versionCode
      //   }
      //   rowData.push(rows)
      // })
      // var data = JSON.stringify(rowData)
       var data = {
         ids:_that.idRow
       }
      guarantorAccountApplyConfirm(data).then(res => {
        // console.log(res);
        _that.disabledBtn = false;
        if (res.httpCode == 200) {
          _that.$message.success("成功");
          _that.dialogTableVisible = false;
          _that.getListInfo();
        }
      }).catch(err => {
        _that.disabledBtn = false;
        // _that.$message.error(err)
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSelectionChangeBatch(val){
      this.multipleSelectionBatch = val;
    },
    handleForBtn(row){
      const _that = this;
      _that.multiChargeData.chargeDate = new Date();
      _that.multiChargeData.payMan = "";
      _that.multiChargeData.idAccount = "";
      _that.multiChargeData.voucherCode = "";
      _that.multiChargeData.chargeKind = "";
      _that.dialogTableVisible = true;
      _that.idRow = row.id
      _that.gridData = [];
      var data = {
        'id': row.id
      }
      getOrderGuarantorInfo(data).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.applyMemo = res.data.applyMemo;
          _that.multiChargeData.chargeDate = new Date()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
      var parms = {
        'idOrder': row.idOrder
      }
      getOrderReceivableByOrder(parms).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.gridData = res.data;
          for (let i = 0; i < _that.gridData.length; i++) {
            _that.$set(_that.gridData[i], 'agioMoney', 0);
            _that.$set(_that.gridData[i], 'receivableMoney', 0);
            _that.$set(_that.gridData[i], 'idReceivable', _that.gridData[i].id);
          }
        } else {
          // _that.$message.error(res.msg)
        }
      }).catch(err => {
        // _that.$message.error(err)
      })
    },
    // 金额分配
    distribute() {
      var _that = this
      var tempMoney = _that.amountMoney
      if (_that.amountMoney > 0) {
        _that.gridData.forEach((item) => {
          if (item.agioMoney > 0) {
            if (parseFloat(item.agioMoney) > item.chargeMoney) {
              _that.$message.error('折扣不能大于应收')
              return
            } else {
              if ((item.chargeMoney - parseFloat(item.agioMoney)) <= tempMoney) {
                item.receivableMoney = (parseInt(item.chargeMoney * 100) - parseFloat(item.agioMoney)*100)*0.01
                // console.log('receivableMoney',item.receivableMoney);
                tempMoney = (tempMoney*100 - item.receivableMoney*100)*0.01
                // console.log('tempMoney', tempMoney)
              } else if ((item.chargeMoney - parseFloat(item.agioMoney)) > tempMoney) {
                item.receivableMoney = tempMoney
                console.log(item.receivableMoney);
                tempMoney = 0
              }
            }
          } else {
            if (item.chargeMoney <= tempMoney) {
              item.receivableMoney = item.chargeMoney
              tempMoney = (tempMoney*100 - item.receivableMoney*100)*0.01
            } else if (item.chargeMoney > tempMoney) {
              item.receivableMoney = tempMoney
              tempMoney = 0
            }
          }
        })
      }
    },
    // 获取列表
    getListInfo() {
      const _that = this
      _that.listLoading = true;
      if (_that.searchTime == null || _that.searchTime < 0) {
        _that.search.applyBeginTime = ''
        _that.search.applyEndTime = ''
      } else {
        _that.search.applyBeginTime = _that.searchTime[0]
        _that.search.applyEndTime = _that.searchTime[1]
      }
      var params = _that.search
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      var data = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }
      // console.log(data);
      orderGuarantorInfoReviewPage(data).then(response => {
        // console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        _that.listData.total = response.total
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err);
        _that.listLoading = false
      })
    },
    // 刷新变革
    tableRefresh() {
      this.getListInfo()
    },
    // 搜索
    searchData() {
      this.listData.page = 1
      this.getListInfo()
    },

    // 获取脚印
    getOrderStep(row) {
      const _that = this
      _that.$refs.orderStep.idOrder = row.idOrder
      _that.$refs.orderStep.getOrderStep()
    },

    // 订单详情
    openDetail(id) {
      var _that = this
      _that.detailVisible = true
      _that.$nextTick(() => {
        _that.$refs.orderDetail.idOrder = id
        _that.$refs.orderDetail.getInfo()
      })
    },
    backBtn(row) {
      var _that = this;
      _that.$confirm('确认退回认款申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        var data = {
          'id': row.id
        }

        guarantorAccountApplyCancel(data).then(res => {
          // console.log(res);
          if (res.httpCode == 200) {
            _that.$message("退回成功")
            _that.getListInfo();
          } else {
            _that.$message.error(res.msg)
          }
        }).catch(err => {
          _that.$message.error(err)
        })
      }).catch(() => {

      })
    },
    // 获取科目
    getAccountInfo() {
      var _that = this
      var data = {}
      getAccountInfoList(data).then(response => {
        _that.accountInfo = response.data;
      }).catch(err => {
        _that.$message.error(err)
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.filter-container{
  margin-bottom: 15px;
}
</style>
