<template>
  <div class="borderless">
    <div class="customer-head">
      <div class="customer-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="info"
                     size="small"
                     :loading="buttonLoading"
                     :disabled="checkDisabled"
                     class="el-button--small-yh"
                     @click.stop="paymentCheck">请核
          </el-button>
          <el-button type="warning"
                     size="small"
                     :loading="buttonLoading"
                     class="el-button--small-yh"
                     :disabled="!checkDisabled"
                     @click.stop="settlement">结算
          </el-button>
          <el-button type="primary"
                     size="small"
                     :loading="buttonLoading"
                     class="el-button--small-yh"
                     @click.stop="confirmEdit">确认修改
          </el-button>
        </div>
      </div>
    </div>
    <div class="customer-main">
      <containerTitle title="基础信息"></containerTitle>
      <basic-container>
        <avue-form class="trading-form" ref="form" v-model="form" :option="option">
          <template slot="corpId">
            <select-component
              v-model="form.corpId"
              @returnBack="returnBack"
              :configuration="configuration"
              :disabled="checkDisabled"
            ></select-component>
          </template>
          <template slot="accountNo">
            <el-select v-model="form.accountNo"
                       placeholder="请选择"
                       @change="accountNoChange"
                       :disabled="checkDisabled"
                       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>
      <containerTitle title="明细列表"></containerTitle>
      <basic-container>
        <avue-crud :option="itemOption"
                   :data="dataList"
                   ref="crud"
                   v-model="itemForm"
                   :page.sync="page"
                   @search-reset="searchReset"
                   @row-update="rowUpdate"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange">
          <template slot-scope="scope" slot="menu">
            <el-button
              type="text"
              size="small"
              :disabled="checkDisabled"
              @click="rowCell(scope.row,scope.index)"
            >{{ scope.row.$cellEdit ? '修改完成' : '修改' }}
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="checkDisabled"
              @click.stop="rowDel(scope.row,scope.index)"
            >删除
            </el-button>
          </template>
          <template slot="costType" slot-scope="{ row }">
            <breakdown-select
              v-if="row.$cellEdit"
              v-model="row.costType"
              :configuration="breakConfiguration">
            </breakdown-select>
            <span v-else>{{ row.itemName }}</span>
          </template>
          <template slot="price" slot-scope="{ row }">
            <el-input
              v-if="row.$cellEdit"
              v-model="row.price"
              placeholder="请输入"
              size="small"
              oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
            ></el-input>
            <span v-else>{{ row.price }}</span>
          </template>
          <template slot="currency" slot-scope="{row,index}">
            <el-select v-if="row.$cellEdit"
                       v-model="row.currency"
                       size="small"
                       @change="currencyChange(row)"
                        clearable
                       filterable>
              <el-option v-for="(item,index) in currencyDic"
                         :key="index"
                         :label="item.dictValue"
                         :value="item.dictValue"></el-option>
            </el-select>
            <span v-else>{{ row.currency }}</span>
          </template>
        </avue-crud>
      </basic-container>
    </div>
  </div>
</template>

<script>
  import itemOption from "./configuration/detailsPage.json";
  import { contrastObj,contrastList } from "@/util/contrastData";
  import { getDetails,modify,submit, paymentCheck,getlistBankBy } from "@/api/financialManagement/paymentRequest";
  import _ from "lodash";

  export default {
    name: "paymentDetailsPage",
    props: {
      detailData: {
        type: Object
      }
    },
    data() {
      return {
        form:{},
        itemForm: {},
        itemOption: itemOption,
        checkDisabled:false,
        buttonLoading:false,
        parentId:0,
        id:"",
        dataList: [],
        currencyDic:[],
        page: {
          pageSize: 10,
          pagerCount: 5,
          total: 0,
        },
        breakConfiguration:{
          multipleChoices:false,
          multiple:false,
          disabled:false,
          searchShow:true,
          collapseTags:false,
          placeholder:'请点击右边按钮选择',
          dicData:[]
        },
        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',
              type:"select",
              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,
              minRows: 2,
              rules: [
                {
                  required: false,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            },
          ],
        },
        //客户组件配置控制
        configuration:{
          multipleChoices:false,
          multiple:false,
          searchShow:true,
          collapseTags:false,
          placeholder:'请点击右边按钮选择',
          dicData:[]
        },
        oldForm:{},
        oldDataList:[],
      }
    },
    created() {
      //是否需要根据 登录人所属公司  区分不用option

      //币别
      this.getWorkDicts("currency").then(res =>{
        this.currencyDic = res.data.data
      })
      if (this.detailData.id) {
        this.id = this.detailData.id;
        this.buttonLoading = true;
        getDetails(this.id).then(res => {
          this.afterEcho(res.data.data)
        }).finally(()=>{
          this.buttonLoading = false
        })
      }
    },
    methods: {
      //选择客户
      returnBack(corpValue){
        getlistBankBy(corpValue).then(res =>{
          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)
          }
        })
      },
      //选择费用
      returnBreak(breakValue){

      },
      //选择币别 带汇率
      currencyChange(row){
        if(row.currency === "CNY"){
            row.exchangeRate = 1
        }else if(row.currency === "USD"){
          row.exchangeRate = 6.384300
        }else{
          row.exchangeRate = 7.174900
        }
      },
      rowUpdate(row, index, done, loading) {
        done(row);
      },
      rowCell(row, index) {
        this.$refs.crud.rowCell(row, index)
      },
      rowDel(row,index){
        this.dataList.splice(index, 1);
      },
      //验证新旧数据
      verification(){
        let verification;
        if(contrastObj(this.form,this.oldForm) || contrastList(this.dataList,this.oldDataList)){
          this.$confirm("您已改动数据,是否先保存在进行操作!", {
            confirmButtonText: "保存",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.confirmEdit()
          }).catch(()=>{
            verification = false;  //取消改动数据
          })
        }else{
          verification = true;   //没有动过数据
        }
        return verification
      },
      //请核
      paymentCheck(){
        if(this.verification()){
          this.$confirm("您确定请核此次申请吗？", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(()=>{
            const params ={
              id : this.form.id,
              billType: this.form.billType
            }
            this.buttonLoading = true
            paymentCheck(params).then(res =>{
              if(res.data.success){
                this.$message.success("请核成功!");
                this.afterEcho(res.data.data)
              }
            }).finally(()=>{
              this.buttonLoading = false
            })
          })
        }
      },
      //结算
      settlement(){
        if(this.verification()){
          if(this.$store.getters.takeStatus){
            this.$alert("结算页面已存在,请关闭收货单再进行操作", "温馨提示", {
              confirmButtonText: "确定",
              type: 'warning',
              callback: action => {
              }
            });
          }else{
            //关闭一下存在的列表页  跳转
            this.$router.$avueRouter.closeTag('/payment_settle');
            this.$router.push({
              path: "/payment_settle",
              query: {params: this.form.id},
            });
          }
        }
      },
      searchReset() {
        console.log('1')
      },
      selectionChange() {
        console.log('1')
      },
      currentChange() {
        console.log('1')
      },
      sizeChange() {
        console.log('1')
      },
      refreshChange() {
        console.log('1')
      },
      confirmEdit(status){
        this.$refs["form"].validate((valid,done) => {
          done();
          if(valid){
            this.form.billNo = this.dataList.map(item =>{return item.billNo}).join(",")

            const params = {
              ...this.form,
              billType:"申请",
              itemsList:this.dataList
            }
            this.buttonLoading = true
            submit(params).then(res =>{
              this.$message.success("操作成功!")
              this.afterEcho(res.data.data)
            }).finally(()=>{
              this.buttonLoading = false
            })
            if(status === true){
              this.$emit("goBack");
            }
          }
        })
      },
      afterEcho(data){
        this.form = data;
        this.oldForm = Object.assign({},data);

        this.checkDisabled = data.checkStatus === "未请核"?false:true;

        this.option.column.forEach(item =>{
          if( item.prop == "remark" ){
            this.$set(item,"disabled",false)
          }else{
            this.$set(item,"disabled",this.checkDisabled)
          }
        })

        if(data.itemsList){
          this.dataList = data.itemsList
          this.oldDataList = this.deepClone(data.itemsList)
        }
      },
      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 lang="scss" scoped>
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
  .trading-form ::v-deep .el-form-item {
    margin-bottom: 8px !important;
  }
  .upper_right_button{
    display: flex;
    position: fixed;
    right: 12px;
    top: 47px;
  }
</style>
