<template>
  <div>
    <containerTitle title="费用明细"></containerTitle>
    <basic-container>
      <avue-crud
        ref="feeCrud"
        :data="feeData"
        :option="feeOption"
        @saveColumn="saveColumn"
        @resetColumn="resetColumn"
        @selection-change="selectionChange"
        :summary-method="summaryMethod"
        :cell-style="cellStyle"
      >
        <template slot="menuLeft">
          <el-tabs v-model="activeName" @tab-click="tabHandle">
            <el-tab-pane label="应收" name="first" :key="'first'">
            </el-tab-pane>
            <el-tab-pane label="应付" name="second" :key="'second'">
            </el-tab-pane>
          </el-tabs>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click.stop="rowAdd"
            :loading="buttonLoading"
            :disabled="disabled"
            >录入明细</el-button
          >
          <el-button
            type="warning"
            size="small"
            @click.stop="billingDetails('收费')"
            :loading="buttonLoading"
            :disabled="
              (financeDisabled && disabled) || selectionList.length == 0
            "
            v-if="selectTab === 1"
            >生成账单</el-button
          >
          <el-button
            type="warning"
            size="small"
            @click.stop="billingDetails('申请')"
            :loading="buttonLoading"
            :disabled="
              (financeDisabled && disabled) || selectionList.length == 0
            "
            v-if="selectTab === 2"
            >申请付费</el-button
          >
        </template>
        <template slot="menu" slot-scope="{ row, index }">
          <el-button
            size="small"
            icon="el-icon-edit"
            type="text"
            @click="rowCell(row, index)"
            :disabled="disabled"
            >{{ row.$cellEdit ? "保存" : "修改" }}</el-button
          >
          <el-button
            size="small"
            icon="el-icon-delete"
            type="text"
            @click="rowDel(row, index)"
            :disabled="disabled"
            >删 除</el-button
          >
        </template>
        <template slot="corpId" slot-scope="{ row, index }">
          <span v-if="row.$cellEdit" class="required_fields">*</span>
          <crop-select
            ref="corp"
            style="width: 90% !important;display: inline-block"
            v-if="row.$cellEdit"
            v-model="row.corpId"
            :cropIndex="index"
            @getCorpData="getCorpData"
            :treeType="optionType"
            corpType="KG"
          ></crop-select>
          <span v-else>{{ row.corpName }}</span>
        </template>
        <template slot="feeName" slot-scope="{ row }">
          <span v-if="row.$cellEdit" class="required_fields">*</span>
          <breakdown-select
            v-if="row.$cellEdit"
            v-model="row.itemId"
            @selectValue="value => selectValue(value, row)"
            :configuration="breakConfiguration"
          >
          </breakdown-select>
          <span v-else>{{ row.feeName }}</span>
        </template>
        <template slot="billNo" slot-scope="{ row }">
          <el-select
            v-if="row.$cellEdit"
            v-model="row.billNo"
            size="small"
            filterable
            allow-create
            default-first-option
            clearable
          >
            <el-option
              v-for="(item, index) in billNoList"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <span v-else>{{ row.billNo }}</span>
        </template>
        <template slot="price" slot-scope="{ row }">
          <el-input
            v-if="row.$cellEdit"
            v-model="row.price"
            placeholder="请输入"
            size="small"
            @input="countChange(row)"
          ></el-input>
          <span v-else>{{ row.price | micrometerFormat }}</span>
        </template>
        <template slot="quantity" slot-scope="{ row }">
          <el-input
            v-if="row.$cellEdit"
            v-model="row.quantity"
            size="small"
            placeholder="请输入"
            oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d\d\d\d\d).*$/, "$1.$2")'
            @input="countChange(row)"
          ></el-input>
          <span v-else>{{ row.quantity | IntegerFormat }}</span>
        </template>
        <template slot="amount" slot-scope="{ row }">
          <span>{{ row.amount | micrometerFormat }}</span>
        </template>
        <template slot="exchangeRate" slot-scope="{ row }">
          <el-input
            v-if="row.$cellEdit"
            v-model="row.exchangeRate"
            size="small"
            oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
            @change="rateChange(row)"
            placeholder="请输入"
          ></el-input>
          <span v-else>{{ row.exchangeRate }}</span>
        </template>
        <template slot="currency" slot-scope="{ row }">
          <el-select
            v-if="row.$cellEdit"
            v-model="row.currency"
            filterable
            allow-create
            default-first-option
            placeholder="请选择"
            size="small"
            @change="currencyChange(row)"
          >
            <el-option
              v-for="(item, index) in currencyList"
              :key="index"
              :label="item.dictValue"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
          <span v-else>{{ row.currency }}</span>
        </template>
        <template slot="unit" slot-scope="{ row }">
          <el-select
            v-if="row.$cellEdit"
            v-model="row.unit"
            filterable
            placeholder="请选择"
            size="small"
          >
            <el-option
              v-for="(item, index) in unitList"
              :key="index"
              :label="item.dictValue"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
          <span v-else>{{ row.unit }}</span>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog
      title="导入费用"
      append-to-body
      :visible.sync="feeDialog"
      top="5vh"
      width="60%"
      :close-on-click-modal="false"
      @closed="feeClose"
      class="el-dialogDeep"
      v-dialog-drag
    >
      <el-row style="height: 0;">
        <el-col :span="5">
          <div style="margin-top:45px">
            <el-scrollbar>
              <basic-container>
                <avue-tree
                  :option="treeOption"
                  :data="treeData"
                  @node-click="nodeClick"
                />
              </basic-container>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <avue-crud
            :option="option"
            :table-loading="loading"
            :data="data"
            ref="crud"
            @refresh-change="refreshChange"
            @selection-change="selectionChange"
            @current-change="currentChange"
            @size-change="sizeChange"
            :page.sync="page"
            @on-load="onLoad"
            :cell-style="cellStyle"
          >
          </avue-crud>
        </el-col>
      </el-row>
      <div class="dialogButton">
        <el-button @click="feeDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="importData"
          :disabled="this.selectionList.length == 0"
        >
          导入
        </el-button>
      </div>
    </el-dialog>
    <crop-dialog ref="cropDialog" @importCorp="importCorp"></crop-dialog>
  </div>
</template>

<script>
import feeOption from "./config/feeInfo.json";
import option from "./config/feeList.json";
import { getDeptLazyTree, customerList } from "@/api/basicData/basicFeesDesc";
import { delItem } from "@/api/feeInfo/fee-info";
import { isPercentage, micrometerFormat, IntegerFormat } from "@/util/validate";
import cropDialog from "@/components/crop-dialog/main";
import _ from "lodash";
import ApplyPayment from "../finance/applyPayment";
import {
  applyLoan,
  paymentApply
} from "@/api/financialManagement/paymentRequest";
import { contrastList } from "@/util/contrastData";
import { allCropList } from "@/api/basicData/customerInformation";
import { getCustomerCode, getCustomerName } from "@/enums/management-type";

export default {
  name: "feeInfo",
  data() {
    return {
      option: option,
      feeOption: {},
      feeDialog: false,
      buttonLoading: false,
      treeOption: {
        nodeKey: "id",
        lazy: true,
        treeLoad: function(node, resolve) {
          const parentId = node.level === 0 ? 0 : node.data.id;
          getDeptLazyTree(parentId).then(res => {
            resolve(
              res.data.data.map(item => {
                return {
                  ...item,
                  leaf: !item.hasChildren
                };
              })
            );
          });
        },
        addBtn: false,
        menu: false,
        size: "small",
        props: {
          labelText: "标题",
          label: "title",
          value: "value",
          children: "children"
        }
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      treeDeptId: null,
      loading: false,
      receivableButton: "primary",
      copeWithButton: "",
      data: [],
      feeData: [],
      selectionList: [],
      reData: null,
      currencyList: [],
      unitList: [],
      breakConfiguration: {
        multipleChoices: false,
        multiple: false,
        disabled: false,
        searchShow: true,
        collapseTags: false,
        clearable: true,
        placeholder: "请点击右边按钮选择",
        dicData: []
      },
      allData: [],
      data_one: [],
      data_two: [],
      selectTab: 1,
      activeName: "first",
      enableName: "first",
      tab1: true,
      tab2: false,
      corpList: []
    };
  },
  props: {
    orderFeesList: {
      type: Array
    },
    disabled: {
      type: Boolean
    },
    feeUrl: {
      type: String
    },
    billUrl: {
      type: String
    },
    optionType: {
      type: String
    },
    itemType: {
      type: String
    },
    srcType: {
      type: Number,
      default: 2
    },
    corpId: {
      type: String
    },
    billNoList: {
      type: Array
    },
    financeDisabled: {
      type: Boolean,
      default: true
    }
  },
  filters: {
    isPercentage(val) {
      return isPercentage(val);
    },
    micrometerFormat(val) {
      return micrometerFormat(val);
    },
    decimalFormat(num) {
      return num ? Number(num).toFixed(2) : "0.00";
    },
    IntegerFormat(num) {
      return IntegerFormat(num);
    }
  },
  async created() {
    this.feeOption = await this.getColumnData(
      this.getColumnName(33),
      feeOption
    );
    if (this.$store.getters.userInfo.tenant_id === "888390") {
      this.feeOption.column.forEach(item => {
        if (item.prop === "billNo") {
          item.hide = false;
        }
      });
    }
    this.getWorkDicts("currency").then(res => {
      this.currencyList = res.data.data;
    });
    this.getWorkDicts("unit").then(res => {
      this.unitList = res.data.data;
    });
    allCropList({
      corpType: getCustomerCode("KG")
    }).then(res => {
      this.corpList = res.data.data;
    });
  },
  components: {
    cropDialog,
    ApplyPayment
  },
  watch: {
    orderFeesList(newVla, oldVal) {
      if (newVla !== oldVal) {
        this.allData = newVla;
        this.data_one = newVla.filter(item => item.feesType === 1); //应收
        this.data_two = newVla.filter(item => item.feesType === 2); //应付
        if (this.selectTab === 1) {
          this.feeData = this.data_one;
        } else {
          this.feeData = this.data_two;
        }
      }
    },
    activeName(newVla, oldVal) {
      if (newVla !== oldVal) {
        if (newVla === "first") {
          this.tab1 = true;
          this.tab2 = false;

          this.data_two = this.feeData;

          this.selectTab = 1;
          this.feeData = this.data_one;
        } else {
          this.tab1 = false;
          this.tab2 = true;

          this.data_one = this.feeData;

          this.selectTab = 2;
          this.feeData = this.data_two;
        }
      }
    }
  },
  methods: {
    //选择费用
    selectValue(value, row) {
      this.$set(row, "feeName", value.cname);
      this.$set(row, "ename", value.ename);
      this.currencyChange(row);
    },
    //选择应收应付
    // handleClick(tab){
    //   if(tab.name === "first"){
    //     this.tab1 = true;
    //     this.tab2 = false;
    //
    //     this.data_two = this.feeData
    //
    //     this.selectTab = 1
    //     this.feeData = this.data_one
    //   }else{
    //     this.tab1 = false;
    //     this.tab2 = true;
    //
    //     this.data_one = this.feeData
    //
    //     this.selectTab = 2
    //     this.feeData = this.data_two
    //   }
    // },
    cellStyle() {
      return "padding:0;height:40px;";
    },
    importCorp(row) {
      this.feeData.push({
        itemId: null,
        corpId: row.id,
        corpName: row.name,
        ename: null,
        feeName: null,
        price: null,
        unit: null,
        quantity: null,
        amount: null,
        currency: "CNY",
        exchangeRate: 1,
        remarks: null,
        $cellEdit: true,
        feesType: this.selectTab
      });
    },
    //带出汇率
    currencyChange(row) {
      this.currencyList.forEach(item => {
        if (item.dictValue === row.currency) {
          this.$set(row, "exchangeRate", item.remark);
        }
      });
    },
    rowDel(row, index) {
      this.$confirm("确定删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //费用判断是否需要调用删除接口
        if (row.id) {
          delItem(row.id, this.feeUrl).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.feeData.splice(index, 1);
          });
        } else {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.feeData.splice(index, 1);
        }
      });
    },
    getCorpData(row) {
      console.log(row);
      this.feeData[row.index].corpName = row.cname;
    },
    countChange(row) {
      if (row.price && row.quantity) {
        row.amount = _.multiply(row.quantity, row.price).toFixed(2);
      }
    },
    rateChange(row) {
      if (row.exchangeRate >= 100) {
        row.exchangeRate = 0;
        this.$message.error("汇率不能超过100%");
      }
    },
    currentChange(val) {
      this.page.currentPage = val;
    },
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
    },
    //刷新
    refreshChange() {
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //多选
    selectionChange(list) {
      this.selectionList = list;
    },
    rePick(row, index) {
      this.reData = {
        ...row,
        index: index
      };
      this.feeDialog = true;

      this.onLoad(this.page);
    },
    //费用编辑
    rowCell(row, index) {
      if (row.$cellEdit == true) {
        this.$set(row, "$cellEdit", false);
      } else {
        this.$set(row, "$cellEdit", true);
      }
    },
    //新增
    rowAdd() {
      if (this.optionType == "CK") {
        this.$refs.feeCrud.rowCellAdd({});
      } else {
        if (this.optionType != "CK") {
          if (!this.corpId) return this.$message.error("请选择往来单位");
        }
        if (this.$store.getters.userInfo.tenant_id === "888390") {
          this.$emit("getBillNo");
        }
        let corpName = this.corpList.find(item => this.corpId == item.id).cname;
        const params = {
          feesType: this.selectTab,
          corpId: this.corpId,
          corpName: corpName
        };
        this.$refs.feeCrud.rowCellAdd(params);
      }
    },
    onLoad(page) {
      this.loading = true;
      let data = {
        size: page.pageSize,
        current: page.currentPage,
        parentId: 0,
        feesTypeId: this.treeDeptId
      };
      customerList(data).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        if (this.page.total) {
          this.option.height = window.innerHeight - 350;
        }
      });
    },
    //导入页左费用类型查询
    nodeClick(data) {
      this.treeDeptId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    feeClose() {
      this.selectionList = [];
      this.page = {
        pageSize: 10,
        currentPage: 1,
        total: 0
      };
      this.treeDeptId = null;
      this.loading = false;
      this.data = [];
      this.reData = null;
    },
    importData() {
      if (this.reData) {
        this.selectionList.length;
        if (this.selectionList.length != 1) {
          return this.$message.error("重新选择的时候只能选择一条数据");
        } else {
          this.selectionList.forEach(e => {
            this.feeData.forEach((item, index) => {
              if (index == this.reData.index) {
                item.itemId = e.id;
                item.corpId = this.reData.corpId;
                item.feeName = e.cname;
                item.price = this.reData.price;
                // item.unit = e.unitno;
                item.quantity = this.reData.quantity;
                item.amount = this.reData.amount;
                item.remarks = this.reData.remarks;
                item.$cellEdit = true;
              }
            });
          });
        }
      } else {
        this.selectionList.forEach(e => {
          this.feeData.push({
            itemId: e.id,
            corpId: null,
            feeName: e.cname,
            price: 0,
            // unit: e.unitno,
            quantity: 0,
            amount: 0,
            remarks: null,
            $cellEdit: true
          });
        });
      }
      this.feeDialog = false;
    },
    submitData() {
      let list = [];
      //保存时  将所出的tab页数据赋值到相应 data上
      if (this.selectTab === 1) {
        this.data_one = this.feeData;
      } else {
        this.data_two = this.feeData;
      }
      list.push(...this.data_one, ...this.data_two);
      return list;
    },

    billingDetails(type) {
      //查看是否改动过数据
      this.$emit("beforeFinance", this.submitData(), params => {
        if (params.valid) {
          for (let i = 0; i < this.selectionList.length; i++) {
            if (this.selectionList[i].corpId != this.selectionList[0].corpId) {
              return this.$message.error("批量操作结算单位必须一致");
            }
            if (this.selectionList[i].isCheck == 1) {
              return this.$message.error(
                "选中的数据已" + type + ",请勿重复操作!"
              );
            }
          }

          this.selectionList.map(item => {
            // item.url = this.billUrl
            item.srcOrderno = params.srcOrderno;
            item.srcParentId = params.parentId;
            item.corpsName = item.corpName;
            item.srcFeesId = item.id;
            item.costType = item.itemId;
            item.itemType = this.itemType;
            item.optionType = this.optionType;
            item.srcType = this.srcType; //费用明细申请
            item.tradeType = this.optionType;
          });
          let data = {
            billType: type,
            itemsList: this.selectionList
          };
          if (type === "申请") {
            this.$confirm("您确定申请付费吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              this.buttonLoading = true;

              data.checkType = "ffsq";
              data.url = "/financialManagement/paymentRequest/index";
              data.pageStatus = "this.$store.getters.pqStatus";
              data.pageLabel = "付费申请";

              applyLoan(data)
                .then(res => {
                  if (res.data.success) {
                    this.$message.success("操作成功!");
                    this.$emit("afterFinance");
                    //跳转付费申请页面
                    // 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.buttonLoading = false;
                });
            });
          } else {
            this.$confirm("您确定生成账单吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              this.buttonLoading = true;
              paymentApply(data)
                .then(res => {
                  if (res.data.success) {
                    this.$message.success("操作成功!");
                    this.$emit("afterFinance");
                  }
                })
                .finally(() => {
                  this.buttonLoading = false;
                });
            });
          }
        }
      });
    },
    summaryMethod({ columns, data }) {
      const sums = [];
      if (columns.length > 0) {
        columns.forEach((item, index) => {
          sums[0] = "合计";
          if (item.property == "quantity" || item.property == "amount") {
            let qtySum = 0;
            let amountSum = 0;
            data.forEach(e => {
              qtySum = _.add(qtySum, Number(e.quantity));
              amountSum = _.add(amountSum, Number(e.amount));
            });
            //数量总计
            if (item.property == "quantity") {
              sums[index] = qtySum ? qtySum.toFixed(2) : "0.00";
            }
            //金额总计
            if (item.property == "amount") {
              sums[index] = micrometerFormat(amountSum);
            }
          }
        });
      }
      return sums;
    },
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(33),
        this.feeOption
      );
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.feeCrud.$refs.dialogColumn.columnBox = false;
      }
    },
    async resetColumn() {
      const inSave = await this.delColumnData(
        this.getColumnName(33),
        feeOption
      );
      if (inSave) {
        this.$message.success("重置成功");
        this.feeOption = feeOption;
        //关闭窗口
        this.$refs.feeCrud.$refs.dialogColumn.columnBox = false;
      }
    },
    tabHandle(data) {
      // if (data.name == this.enableName) return
      // this.enableName = data.name
    }
  }
};
</script>

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