<template>
  <div>
    <basic-container>
      <avue-crud
        ref="crud"
        :data="data"
        :option="option"
        :table-loading="loading"
        @row-update="rowUpdate"
        @row-del="rowDel"
        @saveColumn="saveColumn"
        @resetColumn="resetColumn"
      >
        <template slot="menuLeft" slot-scope="{size}">
          <el-button type="primary"
                     icon="el-icon-plus"
                     size="small"
                     :loading="submitButton"
                     @click="entering"
          >录入
          </el-button>
        </template>
        <template slot-scope="{row,index}" slot="menu">
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="rowCell(row,index)"
          >{{ row.$cellEdit ? '保存' : '修改' }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            size="small"
            @click="rowDel(row,index)"
          >删除</el-button>
        </template>
        <template slot-scope="{row,index}" slot="corpId">
          <span v-if="row.$cellEdit && category != 2" class="required_fields" style="float: left;line-height: 32px">*</span>
          <span v-if="row.$cellEdit && category != 2" style="display: flex">
            <el-select
              v-model="corpId"
              placeholder="请选择"
              size="small"
              style="width:60%"
              filterable
            >
              <el-option
                v-for="item in corpOption"
                :key="item.id"
                :label="item.cname"
                :value="item.id"
              />
            </el-select>
            <el-button
              icon="el-icon-search"
              size="small"
              @click="openDialog(row, index, 1)"
            ></el-button>
          </span>

          <span v-else>{{corpsName}}</span>
        </template>
        <template slot-scope="{row,index}" slot="costType">
          <breakdown-select
            v-if="row.$cellEdit"
            v-model="row.costType"
            style="width: 90%"
            :configuration="configuration"
            @selectValue="(value) => {getFeeValue(row, value)}"
          >
          </breakdown-select>
          <span v-else>{{ row.costName }}</span>
        </template>
        <template slot-scope="{row,index}" slot="billNo">
          <el-select placeholder="请选择"
                     v-if="row.$cellEdit"
                     v-model="row.billNo"
                     size="small"
                     filterable
                     allow-create
                     default-first-option
                     clearable>
            <el-option
              v-for="item in row.billNoList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <span v-else>{{ row.billNo }}</span>
        </template>
        <template slot-scope="{row,index}" slot="taxRate">
          <el-input
            v-model="row.taxRate"
            v-if="row.$cellEdit"
            size="small"
            oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d\d\d\d\d).*$/, "$1.$2")'
            autocomplete="off"
          >
            <i slot="suffix" style="margin-right: 10px;top:6px">%</i>
          </el-input>
          <span v-else>{{ row.taxRate }}</span>
        </template>
        <template slot-scope="{row,index}" slot="currency">
          <span v-if="row.$cellEdit" class="required_fields">*</span>
          <el-select v-if="row.$cellEdit" v-model="row.currency" size="small" placeholder="请选择" style="width: 90%" @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>
        <template slot-scope="{row,index}" slot="unit">
          <el-select  v-if="row.$cellEdit" v-model="row.unit" size="small" style="width: 90%" placeholder="请选择" clearable filterable>
            <el-option v-for="(item,index) in unitDic" :key="index" :label="item.dictValue"  :value="item.dictValue"></el-option>
          </el-select>
          <span v-else>{{ row.unit }}</span>
        </template>
        <template slot-scope="{row,index}" slot="price">
          <el-input-number
            v-if="row.$cellEdit"
            v-model="row.price"
            size="small"
            :controls="false"
            :precision="2"
            @input="amountChange(row)"
            style="width: 100%"
          />
          <span v-else>{{ Number(row.price).toFixed(2) }}</span>
        </template>
        <template slot-scope="{row,index}" slot="quantity">
          <el-input-number
            v-if="row.$cellEdit"
            v-model="row.quantity"
            size="small"
            :controls="false"
            :precision="0"
            @input="amountChange(row)"
            style="width: 100%"
          />
          <span v-else>{{ Number(row.quantity).toFixed(2) }}</span>
        </template>
        <template slot-scope="{row,index}" slot="amount">
          <el-input-number
            v-if="row.$cellEdit"
            v-model="row.amount"
            size="small"
            :controls="false"
            :precision="2"
            style="width: 100%"
          />
          <span v-else>{{ Number(row.amount).toFixed(2) }}</span>
        </template>
      </avue-crud>
      <div class="dialogButton">
        <el-button size="small" :loading="submitButton" @click="$emit('choceFun')">取消</el-button>
        <el-button type="primary" size="small" :loading="submitButton" @click="submit()">确定</el-button>
      </div>
    </basic-container>
    <containerTitle v-if="billId" title="历史账单"></containerTitle>
    <basic-container v-if="billId">
      <avue-crud :option="historyOption"
                 :data="historyDataList"
                 ref="historyCrud"
                 v-model="historyForm"
                 :page.sync="page"
                 :table-loading="historyLoading"
                 @on-load="onLoad">
      </avue-crud>
    </basic-container>

    <el-dialog
      title="客户、供应商"
      :visible.sync="corpVisible"
      width="80%"
      top="5vh"
      append-to-body
      @closed="closeCorp"
      class="el-dialogDeep"
      v-dialog-drag
    >
      <span>
        <el-row>
          <el-col :span="4">
            <el-scrollbar>
              <basic-container>
                <avue-tree
                  :option="corpTreeOption"
                  :data="treeData"
                  @node-click="corpNodeClick"
                  :style="treeStyle"
                />
              </basic-container>
            </el-scrollbar>
          </el-col>
          <el-col :span="20">
            <avue-crud
              :option="KHOption"
              :data="corpData"
              ref="crud"
              :page.sync="corpPage"
              :search.sync="corpSearch"
              @search-change="corpSearchChange"
              @search-reset="corpSearchReset"
              @selection-change="selectionChange"
              @current-change="corpCurrentChange"
              @size-change="corpSizeChange"
              @on-load="corpOnLoad"
              @tree-load="corpTreeLoad"
              @saveColumn="saveColumn"
              @resetColumn="resetColumn"
              @refresh-change="corpRefreshChange"
              :table-loading="dialogLoading"
            >
            </avue-crud>
          </el-col>
        </el-row>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="corpVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="importCorp"
          :disabled="selectionList.length != 1"
        >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {applyLoan, paymentApply} from "@/api/financialManagement/paymentRequest";
  import option from "./config/option.json"
  import historyOption from "../bill/config/application.json"
  import {getUserInfo} from "@/api/system/user";
  import { getBillList } from "@/api/financialManagement/paymentRequest";
  import {customerList, getDeptLazyTree} from "@/api/basicData/customerInformation";
  import { getDeptLazyTree as getFeeLazyTree, customerList as feeList } from "@/api/basicData/basicFeesDesc";
  import corpOption from './config/corpOption.json'

  export default {
    name: "financialAccount",
    props: {
      billId:{
        type:String
      },
      billType: {
        type: String
      },
      srcType: {
        type: Number,
        default: 1,
      },
      billData: {
        type: Object
      },
      choceFun: {
        type: Function
      },
      arrList: {
        type: Array,
        default: []
      },
      checkData: {
        type: Object,
        default: {
          url: null,
          pageStatus: null,
          pageLabel: null,
          checkType: null
        },
      },
      belongCompany: {
        type: String,
      }
    },
    data(){
      return {
        data: [],
        corpId:'',
        corpsName: '',
        option:option,
        loading:false,
        submitButton:false,
        currencyDic:[],
        unitDic:[],
        configuration: {
          multipleChoices: false,
          multiple: false,
          disabled: true,
          searchShow: true,
          collapseTags: false,
          placeholder: '请点击右边按钮选择',
          dicData: []
        },
        category: '',

        historyLoading:false,
        historyOption:historyOption,
        historyDataList:[],
        historyForm:{},
        page: {
          pageSize: 10,
          pagerCount: 1,
          total: 0,
        },
        corpOption: [], //客户
        feeOption: [], // 费用
        rowData: null,
        corpVisible: false,
        feeVisible: false,
        treeStyle:'height:'+(window.innerHeight - 315)+'px',
        corpTreeOption: {
          nodeKey: "id",
          lazy: true,
          addBtn: false,
          menu: false,
          size: "small",
          props: {
            labelText: "标题",
            label: "title",
            value: "value",
            children: "children"
          }
        },
        treeCorpId: '',
        selectionList: [],
        corpPage: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        corpSearch: {},
        dialogLoading: false,
        KHOption: corpOption,
        corpData: [],
      }
    },
    created() {
      this.option.height = window.innerHeight - 240;
      this.historyOption.searchShow = false
      customerList({
        size: 10000,
        current: 1
      }).then(res => {
        // this.corpOption = res.data.data.records? res.data.data.records: [];
        if (res.data.data.total > 0) {
          this.corpOption = res.data.data.records;
          if (Math.ceil(res.data.data.total / 10) > 1) {
            for (let i = 2; i <= Math.ceil(res.data.data.total / 10); i++) {
              customerList({current: i, size: 10}).then(e => {
                this.corpOption = this.corpOption.concat(e.data.data.records);
              });
            }
          }
        }
      })
      this.loading = true;
      feeList({size: 10000, current: 1}).then(res => {
        this.feeOption = res.data.data.records? res.data.data.records: [];
        this.init()
      }).finally(() => {
        this.loading = false;
      })
      getUserInfo().then(res=>{
        this.category = res.data.data.billType
        if (this.category == 2) {
        }
      })
      //币别
      this.getWorkDicts("currency").then(res => {
        this.currencyDic = res.data.data
      })
      this.getWorkDicts("unit").then(res => {
        this.unitDic = res.data.data
      })
    },
    mounted() {
      // this.init()
    },
    watch:{
      billId(val, oldVal) {
        if(val != oldVal){
          this.onLoad(this.page)
        }
      },
    },
    methods:{
      init(){
        if(this.arrList.length === 0){
          this.corpId = this.billData.corpId
          this.corpsName = this.billData.corpsName[0].cname
          this.feeOption.forEach(item => {
            if (this.billData.costType == item.id) {
              this.$set(this.billData, 'costName', item.cname)
            }
          })
          this.data.push(this.billData)
        }else{
          this.billData = this.arrList[0]
          this.corpId = this.arrList[0].corpId
          this.corpsName = this.arrList[0].corpsName[0].cname
          this.arrList.forEach(item=>{
            this.feeOption.forEach(e => {
              if (item.costType == e.id) {
                this.$set(item, 'costName', e.cname)
              }
            })
            this.data.push(item)
          })
        }

        //删除 提单号
        if(this.billData.optionType !== "JK"){
          this.option.column.forEach(item =>{
            if(item.prop === "billNo"){
              item.hide = true
            }else{
              item.hide = false
            }
          })
        }
      },
      currencyChange(row){
        this.currencyDic.forEach(item =>{
          if(item.dictValue === row.currency){
            row.exchangeRate = item.remark
          }
        })
      },
      rowCell(row,index){
        // this.$refs.crud.rowCell(row, index)
        if (row.$cellEdit == true) {
          this.$set(row, '$cellEdit', false)
        } else {
          this.$set(row, '$cellEdit', true)
        }
      },
      rowDel(row,index){
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
            this.data.splice(index, 1);
         })
      },
      rowUpdate(row, index, done, loading) {
        done(row);
      },
      entering(){
        if(this.data.length !== 0){
          //取第一条数据的 合同号 以及客户
          let params = {
            ...this.billData,
            srcOrderno:this.data[0].srcOrderno,
            corpId:this.data[0].corpId
          }
          this.$refs.crud.rowCellAdd(params);
        }else{
          this.$refs.crud.rowCellAdd(this.billData);
        }
      },
      onLoad(page,params = {}) {
        this.historyLoading = true;
        params.srcParentId = this.billId
        params.flag = 1

        getBillList(page.currentPage, page.pageSize,params).then(res=>{
          this.historyDataList = res.data.data.records
        }).finally(()=>{
          this.historyLoading = false;
        })
      },
      submit(){
        for(let i = 0;i<this.data.length;i++){
          if (this.corpId === (null || "")) {
            return this.$message.error(`请输入第${i + 1}行的客户`);
          }
          if (this.data[i].costType === (null || "")) {
            return this.$message.error(`请输入第${i + 1}行的费用名称`);
          }
          if (this.data[i].accDate === (null || "")) {
            return this.$message.error(`请输入第${i + 1}行的合同日期`);
          }
          if (this.data[i].amount === (null || "")) {
            return this.$message.error(`请输入第${i + 1}行的金额`);
          }
          if (this.data[i].currency === (null || "")) {
            return this.$message.error(`请输入第${i + 1}行的币别`);
          }
          if (this.data[i].exchangeRate === (null || "")) {
            return this.$message.error(`请输入第${i + 1}行的汇率`);
          }
          if (this.data[i].taxRate === (null || "")) {
            return this.$message.error(`请输入第${i + 1}行的税率`);
          }
        }

        this.submitButton = true
        const itemsList = this.data.map(item => {
          item.corpId = this.corpId;
          item.tradeType = this.billData.optionType?this.billData.optionType: item.tradeType;
          item.srcType = item.srcType? item.srcType: this.srcType;
          return item;
        })
        const params = {
          url: this.checkData.url,
          pageStatus: this.checkData.pageStatus,
          pageLabel: this.checkData.pageLabel,
          checkType: this.checkData.checkType,
          billType : this.billType,
          DC : this.billData.itemType === "采购"?"C":"D",     //账单明细会根据D C区分采购 销售搜索
          itemsList: itemsList,
          belongCompany: this.belongCompany // 所属公司
        }
        // 采购申请货款   销售申请退款 都会走申请 走审核   => 付款申请
        if(this.billType === "申请"){
          applyLoan(params).then(res =>{
            if(res.data.success){
              this.$message.success("操作成功!")
              this.$emit("choceFun");
              this.$emit("submit")
              //跳转付款申请页面

              // if(this.$store.getters.pqStatus){
              //   this.$alert("无法自动跳,因为付费申请页面已存在!", "温馨提示", {
              //     confirmButtonText: "确定",
              //     type: 'warning',
              //     callback: action => {
              //     }
              //   });
              // }else{
              //   //关闭一下存在的列表页  跳转
              //   this.$router.$avueRouter.closeTag('/financialManagement/paymentRequest/index');
              //   this.$router.push({
              //     path: "/financialManagement/paymentRequest/index",
              //     query: {params: res.data.data.id},
              //   });
              // }
            }
          }).finally(()=>{
            this.submitButton = false
          })
        }
        //采购退款结算 销售收款结算  不需申请请核 直接结算  => 结算
        if(this.billType === "收费"){
          paymentApply(params).then(res=>{
            if(res.data.success){
              this.$message.success("操作成功!")
              this.$emit("choceFun");
              this.$emit("submit")
            }
          }).finally(()=>{
            this.submitButton = false
          })
        }
      },
      saveColumn(){

      },
      resetColumn(){

      },
      amountChange(row) {
        if (!row.quantity) {
          row.quantity = 0;
        }
        if (!row.price) {
          row.price = 0;
        }
        row.amount = Number(row.price) * Number(row.quantity)
      },
      // 客户、费用弹窗
      openDialog(row, index, type) {
        this.rowData = {
          ...row,
          index
        }
        // 1客户 2费用
        if (type == 1) {
          this.corpTreeOption.treeLoad = function(node, resolve) {
            const parentId = node.level === 0 ? 0 : node.data.id;
            getDeptLazyTree({
              parentId: parentId,
              corpType: "KG"
            }).then(res => {
              resolve(
                res.data.data.map(item => {
                  return {
                    ...item,
                    leaf: !item.hasChildren
                  };
                })
              );
            });
          };
          this.corpVisible = !this.corpVisible;
        } else if (type == 2) {
          this.feeVisible = !this.feeVisible;
        }
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      closeCorp() {
        this.selectionList = [];
        this.treeCorpId = "";
        this.reData = null;
      },
      corpNodeClick(data) {
        this.treeCorpId = data.id;
        this.corpPage.currentPage = 1;
        this.corpOnLoad(this.corpPage);
      },
      //列表内展开树节点
      corpTreeLoad(tree, treeNode, resolve) {
        const parentId = tree.id;
        customerList({ parentId: parentId }).then(res => {
          resolve(res.data.data.records);
        });
      },
      //点击搜索按钮触发
      corpSearchChange(params, done) {
        this.corpPage.currentPage = 1;
        this.corpOnLoad(this.corpPage, params);
        done();
      },
      corpSearchReset() {
        this.treeCorpId = null;
      },
      corpSizeChange(val) {
        this.corpPage.pageSize = val;
        this.corpOnLoad();
      },
      corpCurrentChange(val) {
        this.corpPage.currentPage = val;
        this.corpOnLoad();
      },
      corpRefreshChange() {
        this.corpOnLoad(this.corpPage, this.corpSearch);
      },
      corpOnLoad(page, params = { parentId: 0 }) {
        let queryParams = Object.assign({}, params, {
          size: page.pageSize,
          current: page.currentPage,
          corpsTypeId: this.treeDeptId,
          corpType: 'KG'
        });
        this.dialogLoading = true;
        customerList(queryParams)
          .then(res => {
            this.corpData = res.data.data.records;
            this.corpPage.total = res.data.data.total;
            if (this.corpPage.total) {
              this.KHOption.height = window.innerHeight - 350;
            }
          })
          .finally(() => {
            this.dialogLoading = false;
          });
      },
      importCorp() {
        this.corpData.forEach((item, index) => {
          if (index == this.rowData.index) {
            item.corpId = this.selectionList[0].id;
          }
        })
        this.corpVisible = false;
      },
      getFeeValue(row, value) {
        this.$set(row, 'costName', value.cname)
      }
    }
  }
</script>

<style scoped lang="scss">
  .required_fields{
    color: #F56C6C;
    display:inline-block;
    width: 7%
  }
</style>
