<template>
  <div>
    <containerTitle title="费用明细"></containerTitle>
    <basic-container>
      <avue-crud
        ref="feeCrud"
        :data="feeData"
        :option="feeOption"
        @saveColumn="saveColumn"
        :summary-method="summaryMethod"
      >
        <template slot="menuLeft">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click.stop="rowAdd"
            :disabled="disabled"
            >新增</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 }">
          <customer-dialog
            v-if="row.$cellEdit"
            v-model="row.corpName"
            :cropIndex="index"
            @getcorpId="getcorpId"
          ></customer-dialog>
          <span v-else>{{ row.corpName }}</span>
        </template>
        <template slot="feeName" slot-scope="{ row, index }">
          <el-button
            size="small"
            type="text"
            @click="rePick(row, index)"
            :disabled="disabled || !row.$cellEdit"
            class="picker"
            style="padding:4px 10px;float:left"
            >选择</el-button
          >
          <span> {{ row.feeName }}</span>
        </template>
        <template slot="price" slot-scope="{ row }">
          <el-input
            v-if="row.$cellEdit"
            v-model="row.price"
            size="small"
            oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
            @change="priceChange(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"
            oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
            @change="quantityChange(row)"
          ></el-input>
          <span v-else>{{ row.quantity }}</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 | isPercentage }}</span>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog
      title="导入费用"
      append-to-body
      :visible.sync="feeDialog"
      width="60%"
      :close-on-click-modal="false"
      @closed="feeClose"
      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"
          >
          </avue-crud>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="feeDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="importData"
          :disabled="this.selectionList.length == 0"
        >
          导入
        </el-button>
      </span>
    </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 } from "@/util/validate";
import customerDialog from "@/components/customer-dialog/main";
import cropDialog from "@/components/crop-dialog/main";
import _ from "lodash";
export default {
  name: "feeInfo",
  data() {
    return {
      option: option,
      feeOption: {},
      feeDialog: 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,
      data: [],
      feeData: [],
      selectionList: [],
      reData: null
    };
  },
  props: {
    orderFeesList: {
      type: Array
    },
    disabled: {
      type: Boolean
    },
    feeUrl: {
      type: String
    }
  },
  filters: {
    isPercentage(val) {
      return isPercentage(val);
    },
    micrometerFormat(val) {
      return micrometerFormat(val);
    }
  },
  async created() {
    this.feeOption = await this.getColumnData(
      this.getColumnName(33),
      feeOption
    );
  },
  components: {
    customerDialog,
    cropDialog
  },
  methods: {
    importCorp(row) {
      this.feeData.push({
        itemId: null,
        corpId: row.id,
        corpName: row.name,
        feeName: null,
        price: null,
        unit: null,
        quantity: null,
        amount: null,
        currency: null,
        exchangeRate: null,
        remarks: null,
        $cellEdit: true
      });
    },
    getcorpId(row) {
      this.feeData[row.index].corpId = row.id;
    },
    rowDel(row, index) {
      console.log(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);
        }
      });
    },
    priceChange(row) {
      if (!row.price) {
        row.price = 0;
      } else {
        row.amount = _.multiply(row.price, row.quantity).toFixed(2);
      }
    },
    quantityChange(row) {
      if (!row.quantity) {
        row.quantity = 0;
      } else {
        row.amount = _.multiply(row.price, row.quantity).toFixed(2);
      }
    },
    rateChange(row) {
      row.exchangeRate;
      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.option.height = window.innerHeight - 500;
      this.onLoad(this.page);
    },
    //费用编辑
    rowCell(row, index) {
      if (row.$cellEdit == true) {
        this.$set(row, "$cellEdit", false);
      } else {
        this.$set(row, "$cellEdit", true);
      }
    },
    //新增
    rowAdd() {
      this.$refs.cropDialog.init();
    },
    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;
      });
    },
    //导入页左费用类型查询
    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.currency = e.fcyno;
                item.exchangeRate = this.reData.exchangeRate;
                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,
      //       currency: e.fcyno,
      //       exchangeRate: null,
      //       remarks: null,
      //       $cellEdit: true
      //     });
      //   });
      // }
      this.feeDialog = false;
    },
    submitData() {
      return this.feeData;
    },
    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;
      }
    }
  },
  watch: {
    orderFeesList: function(rows) {
      this.feeData = rows ? rows : [];
    }
  }
};
</script>

<style lang="scss" scoped></style>
