<template>
  <div>
    <div v-for="(item, index) in list" :key="index">
      <el-row>
        <el-col :span="24"><span class="delete_group" v-if="list.length !== 1" @click="deleteGroup(index)">删除组</span>
        </el-col>
      </el-row>
      <basic-container>
        <avue-form class="trading-form" :option="option" ref="form" v-model="item.form">
          <template slot-scope="scope" slot="corpId">
            <selectComponent v-model="item.form.corpId" :configuration="configuration"/>
          </template>
          <template slot-scope="scope" slot="billNo">
            <el-select placeholder="请选择" v-model="item.form.billNo" clearable>
              <el-option
                v-for="item in item.form.billNoList"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </template>
          <template slot-scope="scope" slot="costType">
            <breakdown-select
               v-model="item.form.costType"
               :configuration="breakConfiguration">
            </breakdown-select>
          </template>
         <!-- <template slot-scope="scope" slot="price">
            <el-input
              v-model="item.form.price"
              autocomplete="off"
              placeholder="请输入 单价"
              @input="calculate(item.form)"
            ></el-input>
          </template>
          <template slot-scope="scope" slot="quantity">
            <el-input
              v-model="item.form.quantity"
              autocomplete="off"
              placeholder="请输入 数量"
              @input="calculate(item.form)"
            ></el-input>
          </template>-->
          <template slot-scope="scope" slot="currency">
            <el-select v-model="item.form.currency" size="small" placeholder="请选择 币别" @change="currencyChange(item.form)" clearable filterable>
              <el-option v-for="(item,index) in currencyDic" :key="index" :label="item.dictValue"  :value="item.dictValue"></el-option>
            </el-select>
          </template>
       </avue-form>
      </basic-container>
    </div>
    <el-button style="margin: 8px;" icon="el-icon-plus" size="small" @click="addForm">
       添加账单
    </el-button>
    <div style="float: right;margin: 8px">
      <el-button size="small" @click="$emit('choceFun')">取消</el-button>
      <el-button type="primary" size="small" @click="submit()">确定</el-button>
    </div>
  </div>
</template>

<script>
import {applyLoan, paymentApply} from "@/api/financialManagement/paymentRequest";
import _ from "lodash";

export default {
  name: "applyPayment",
  props: {
    billType: {
      type: String
    },
    billData: {
      type: Object
    },
    choceFun: {
      type: Function
    },
    arrList: {
      type: Array,
      default: []
    }

  },
  data() {
    return {
      form: {
        form: {}
      },
      list: [],
      currencyDic: [],
      corpId: "",
      configuration: {
        multipleChoices: false,
        multiple: false,
        disabled: true,
        searchShow: true,
        collapseTags: false,
        placeholder: '请点击右边按钮选择',
        dicData: []
      },
      breakConfiguration: {
        multipleChoices: false,
        multiple: false,
        disabled: true,
        searchShow: true,
        collapseTags: false,
        placeholder: '请点击右边按钮选择',
        dicData: []
      },
      option: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: 120,
        menuSpan: 8,
        column: [
          {
            label: this.billData.optionType === "JK" ? "合同号" : "订单号",
            prop: 'srcOrderno',
            span: 8,
            disabled: true,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '客户名称',
            prop: 'corpId',
            span: 16,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          this.billData.optionType === "JK" ?
            {
              label: '提单号',
              prop: 'billNo',
              span: 8,
              rules: [
                {
                  required: true,
                  message: ' ',
                  trigger: 'blur'
                }
              ]
            } : {display: false},
          {
            label: '费用名称',
            prop: 'costType',
            span: 8,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: this.billData.optionType === "JK" ? '合同日期' : "订单日期",
            type: "date",
            prop: 'accDate',
            span: 8,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '单价',
            prop: 'price',
            span: 8,
            rules: [
              {
                pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                message: ' ',
                trigger: 'blur'
              },
              {
                required: true,
                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'
              },
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: this.billData.itemType === "采购" ? '付款日期' : "收款日期",
            prop: 'date',
            type: 'date',
            span: 8,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '计价单位',
            prop: 'unit',
            type: "select",
            span: 8,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ],
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=unit",
            props: {
              label: "dictValue",
              value: "dictKey"
            }
          },
          {
            label: '币别',
            prop: 'currency',
            span: 8,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=currency",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '汇率',
            prop: 'exchangeRate',
            span: 8,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '税率',
            prop: 'taxRate',
            span: 8,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remarks',
            span: 24,
            type: 'textarea',
            row: true,
            minRows: 2,
            isRules: false
          }
        ]
      },
    }
  },
  created() {
    //币别
    this.getWorkDicts("currency").then(res => {
      this.currencyDic = res.data.data
    })
    if (this.arrList.length == 0) {
      this.form.form = this.billData
      this.corpId = this.billData.corpId
      this.configuration.dicData = this.billData.corpsName
      this.addForm();
    }
    if (this.arrList.length > 0) {
      this.list = this.arrList
      let arr = []
      this.list.forEach(item => {
        let a = {
          id: item.form.corpId,
          cname: item.form.corpsName
        }
        arr.push(a)
      })
      this.configuration.dicData = this.configuration.dicData.concat(arr)
    }
  },
  methods: {
    addForm() {
      //去除form身上双向绑定
      this.list.push(JSON.parse(JSON.stringify(this.form)))
    },
    deleteGroup(index) {
      this.list.splice(index, 1);
    },
    //计算单价  数量
    // calculate(valueForm){
    //   if(valueForm.price && valueForm.quantity){
    //     valueForm.amount = _.multiply(valueForm.price, valueForm.quantity).toFixed(2);
    //   }
    // },
    //币别选择
    currencyChange(valueForm) {
      if (valueForm.currency === "USD") {
        valueForm.exchangeRate = 6.3686;
      } else {
        valueForm.exchangeRate = 1;
      }
    },
    async submit() {
      let result = [];
      await this.handleRulesValid(["form"], result)
      if (result.some(item => item)) {
        const itemsList = this.list.map(item => {
          item.form.corpId = this.corpId;
          return item.form
        })

            const params = {
              billType : this.billType,
              DC : this.billData.itemType === "采购"?"C":"D",     //账单明细会根据D C区分采购 销售搜索
              itemsList: itemsList
            }
            // 采购申请货款   销售申请退款 都会走申请 走审核   => 付款申请
            if(this.billType === "采购申请货款" || this.billType === "销售申请退款" ){
              applyLoan(params).then(res =>{
                if(res.data.success){
                  this.$message.success("操作成功!")
                  this.$emit("choceFun");
                  //跳转付款申请页面
                  if(this.$store.getters.pqStatus){
                    this.$alert("无法自动跳转到付款申请页面,因为页面已存在。", "温馨提示", {
                      confirmButtonText: "确定",
                      type: 'warning',
                      callback: action => {
                      }
                    });
                  }else{
                    //关闭一下存在的列表页  跳转
                    this.$router.$avueRouter.closeTag('/payment_request');
                    this.$router.push({
                      path: "/payment_request",
                      query: {params: res.data.data.id},
                    });
                  }
                }
              })
            }
            //采购退款结算 销售收款结算  不需申请请核 直接结算  => 结算
            if(this.billType === "采购退款结算" || this.billType === "销售收款结算"){
              paymentApply(params).then(res=>{
                if(res.data.success){
                  this.$message.success("操作成功!")
                  this.$emit("choceFun");
                }
              })
            }
          }
        },
        /**
         * @param instance 实例
         * @param result 校验结果数组
         * 递归校验每个表格实例
         */
        handleValid(instance,result) {
          if(!instance) {
            result.push(true)
          }else if(Array.isArray(instance)) {
            instance.map(item => this.handleValid(item,result))
          }else{
            if(instance.validate) {
              instance.validate(valid => {
                result.push(valid)
                instance.hide && instance.hide()
              })
            }else {
              instance.validateCellForm().then(msg=>{
                if((msg && !Object.keys(msg).length) || undefined === msg){
                  result.push(true)
                }else{
                  result.push(false)
                }
              })
            }

          }
        },
        /**
         * @param resultArr 校验结果数组
         * 统一校验方法
         */
        handleRulesValid(refsList,resultArr) {
          refsList.map(item => this.handleValid(this.$refs[`${item}`],resultArr))
        }
      }
    }
</script>

<style  lang="scss" scoped>
.delete_group{
  display: inline-block;
  line-height: 50px;
  color: #b80000;
  margin-right: 20px;
  float: right;
}
.trading-form ::v-deep .el-form-item {
  margin-bottom: 8px !important;
}
</style>
