<template>
  <div class="borderless">
    <div class="main-head">
      <div class="main-back">
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                   @click="backToList">返回列表
        </el-button>
        <div class="upper_right_button">
          <el-button type="warning"
                     class="el-button--small-yh"
                     @click.stop="confirmSettlement"
          >结算
          </el-button>
          <el-button class="el-button--small-yh"
                     type="primary"
                     @click.stop="confirmSettlement"
          >{{this.id?"确认修改" :"确认新增"}}
          </el-button>
        </div>
      </div>
    </div>
    <div style="margin-top: 60px">
      <containerTitle title="基础信息"></containerTitle>
      <basic-container>
        <avue-form ref="form" v-model="form" :option="option">
          <template slot="corpId">
            <select-component
              v-model="form.corpId"
              @returnBack="returnBack"
              :configuration="configuration"
            ></select-component>
          </template>
          <template slot="accountNo">
            <el-select v-model="form.accountNo"
                       placeholder="请选择"
                       @change="accountNoChange"
                       clearable
                       filterable>
              <el-option v-for="(item,index) in form.bankList"
                         :key="index"
                         :label="item.accountNo"
                         :value="item.accountNo"
              >
              </el-option>
            </el-select>
          </template>
        </avue-form>
      </basic-container>
      <basic-container>
        <avue-crud :option="itemsOption"
                   :data="dataList"
                   ref="crud"
                   v-model="itemsForm"
                   :page.sync="page"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange">
          <template slot="menuLeft">
            <el-button type="primary"
                       size="small"
                       icon="el-icon-shopping-cart-2"
                       @click="selectPurchase">选择采购合同
            </el-button>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button
              type="text"
              size="small"
              @click.stop="rowCell(scope.row,scope.index)"
            > {{ scope.row.$cellEdit ? '修改完成' : '修改' }}
            </el-button>
            <el-button
              type="text"
              size="small"
              @click.stop="rowDel(scope.row,scope.index)"
            >删除
            </el-button>
          </template>
          <template slot="thisAmount" slot-scope="{ row }">
            <el-input
              v-if="row.$cellEdit"
              v-model="row.thisAmount"
              placeholder="请输入"
              size="small"
              oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
              @change="thisAmountChange(row)"
            ></el-input>
            <span v-else>{{ row.thisAmount }}</span>
          </template>
        </avue-crud>
      </basic-container>
      <el-dialog
        title="导入采购"
        append-to-body
        class="el-dialogDeep"
        :visible.sync="billDetailDialog"
        width="60%"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :close-on-press-escape="false"
        top="10vh"
        v-dialog-drag>
        <bill-detail
          :corpId="corpId"
          :billType="billType"
          @closeFun="!billDetailDialog"
          @importProMent="importProMent"
        >
        </bill-detail>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import option from "./configuration/detailsPage.json";
  import { getDetail,editFinance } from "@/api/financialManagement/financialManagement"
  import { getDetails,modify } from "@/api/financialManagement/paymentRequest";
  import { contrastObj,contrastList } from "@/util/contrastData";
  import  billDetail from "@/components/bill/billDetailList";
  import { getlistBankBy } from "@/api/financialManagement/paymentRequest";
  import _ from "lodash";

  export default {
    name: "paymentDetailsPage",
    props: {
      detailData: {
        type: Object
      }
    },
    data() {
      return {
        form: {},
        itemsForm:{},
        itemsOption: option,
        billDetailDialog:false,
        billType:"申请",
        corpId:"",
        id:"",
        dataList: [],
        currencyDic:[],
        page: {
          pageSize: 10,
          pagerCount: 5,
          total: 0,
        },
        query:{},
        option: {
          menuBtn: false,
          labelWidth: 100,
          column: [
            {
              label: '系统号',
              prop: 'sysNo',
              span: 8,
              disabled: true
            },{
              label: '合同号',
              prop: 'srcOrderno',
              span: 8,
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            }, {
              label: '客户名称',
              prop: 'corpId',
              sort:true,
              span: 8,
              rules: [
                {
                  required: false,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '银行账号',
              prop: 'accountNo',
              span: 8,
              rules: [
                {
                  required: false,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '开户银行',
              prop: 'accountBank',
              span: 8,
              rules: [
                {
                  required: false,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            }, {
              label: '银行户头',
              prop: 'accountName',
              span: 8,
              rules: [
                {
                  required: false,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '总金额',
              prop: 'amount',
              span: 8,
              rules: [
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '制单人',
              prop: 'createUserName',
              span: 8,
              disabled:true,
              rules: [
                {
                  required: false,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            }, {
              label: '制单日期',
              prop: 'createTime',
              span: 8,
              type:"date",
              disabled:true,
              rules: [
                {
                  required: false,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '备注',
              prop: 'remark',
              span:24,
              row:2,
              rules: [
                {
                  required: false,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
          ],
        },
        //客户组件配置控制
        configuration:{
          multipleChoices:false,
          multiple:false,
          disabled:false,
          searchShow:true,
          collapseTags:false,
          placeholder:'请点击右边按钮选择',
          dicData:[]
        },
        financeStatusDic:[{
          label:'正常',
          value:0
        },{
          label:'停用',
          value:1
        }],
        //顶部from数据
        oldForm:{},
        oldDataList:[],
      }
    },
    components:{
      billDetail
    },
    created() {
      //币别
      this.getWorkDicts("currency").then(res =>{
        this.currencyDic = res.data.data
      })
      if (this.detailData.id) {
        this.id = BigInt(this.detailData.id);//字符串转数字  超长用BigInt
        getDetail(this.id).then(res => {
          this.form = res.data.data;
          this.oldForm = Object.assign({},res.data.data);
          if(res.data.data.itemsList){
            this.dataList = res.data.data.itemsList
            this.oldDataList = this.deepClone(res.data.data.itemsList)
          }
        })
      }

      if(this.detailData.params){
        getDetails(this.detailData.params).then(res =>{
          delete res.data.data.id;
          delete res.data.data.sysNo;
          delete res.data.data.billType;
          res.data.data.itemsList.map((items)=>{
            delete items.id ;
            items.thisAmount = items.amount
          })
          this.form = res.data.data;
          this.oldForm = Object.assign({},res.data.data);
          if(res.data.data.itemsList){
            this.dataList = res.data.data.itemsList
            this.oldDataList = this.deepClone(res.data.data.itemsList)
          }
        })
      }
    },
    mounted() {
      option.height = window.innerHeight - 640 ;
    },
    methods: {
      //选择客户
      returnBack(corpValue){
        this.corpId = corpValue
        getlistBankBy(corpValue).then(res =>{
          this.$set(this.form,"bankList",res.data)
        })
      },
      //选择卡号
      accountNoChange(value){
        this.form.bankList.forEach(item =>{
          if(item.accountNo == value){
            this.$set(this.form,"accountBank",item.accountBank)
            this.$set(this.form,"accountName",item.accountName)
          }
        })
      },
      thisAmountChange(row){
        if(row.thisAmount > row.amount){
          this.$message.error("本次金额不得大于金额!")
          row.thisAmount = 0;
        }
      },
      selectPurchase(){
        this.billDetailDialog = true;
      },
      importProMent(list){
        list.forEach((item,index) =>{
          item.accId = item.id;
          delete item.id;
          this.$refs.crud.rowCellAdd(item);
        })
        this.billDetailDialog = false;
      },
      rowCell(row,index){
        this.$refs.crud.rowCell(row, index)
      },
      rowDel(row,index){
        this.dataList.splice(index, 1);
      },
      searchReset() {
        console.log('1')
      },
      selectionChange() {
        console.log('1')
      },
      currentChange() {
        console.log('1')
      },
      sizeChange() {
        console.log('1')
      },
      refreshChange() {
        console.log('1')
      },
      confirmSettlement(status){
        this.$refs["form"].validate((valid) => {
          if(valid){
            this.$confirm("是否确认结算？", "提示", {
              confirmButtonText: "保存",
              cancelButtonText: "取消",
              type: "warning",
            }).then(()=>{
              for (let i = 0; i < this.dataList.length; i++) {
                if (this.dataList[i].thisAmount == null) {
                  return this.$message.error(`第${i + 1}行的本次金额不能为空`);
                }
                if (this.dataList[i].thisAmount === 0) {
                  return this.$message.error(`第${i + 1}行的本次金额不能为0`);
                }
              }

              this.form.billNo = this.dataList.map(item =>{return item.billNo}).join(",")

              const params = {
                ...this.form,
                billType:"付费",
                itemsList:this.dataList
              }

              modify(params).then(res =>{
                this.$message.success("操作成功!")
                this.form = res.data.data;
                this.oldForm = Object.assign({},res.data.data);
                if(res.data.data.itemsList){
                  this.dataList = res.data.data.itemsList
                  this.oldDataList = this.deepClone(res.data.data.itemsList)
                }
              })
            })
            if(status === true){
              this.$emit("goBack");
            }
          }
        })
      },
      backToList() {
        if(contrastObj(this.form,this.oldForm) || contrastList(this.dataList,this.oldDataList)
        ){
          this.$confirm("是否保存当前页面？", "提示", {
            confirmButtonText: "保存",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.editCustomer(true)
          }).catch(()=>{
            this.$emit("goBack");
          })
        }else{
          this.$emit("goBack");
        }
      },
    }
  }
</script>

<style scoped>
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
  .main-head {
    position: fixed;
    top: 105px;
    width: 100%;
    margin-left: -10px;
    height: 62px;
    background: #ffffff;
    box-shadow: 0 4px 12px 0px rgba(232, 232, 235, 1);
    z-index: 999;
  }
  .main-back {
    cursor: pointer;
    line-height: 62px;
    font-size: 16px;
    color: #323233;
    font-weight: 400;
  }
  .upper_right_button{
    display: flex;
    position: fixed;
    right: 20px;
    top: 115px;
  }
</style>
