<template>
  <div>
    <avue-crud
      :option="option"
      :data="pageData"
      id="out-table"
      ref="crud"
      @selection-change="handleSelectionChange"
      :header-cell-style="tableHeaderCellStyle"
      :row-class-name="rowClassName"
      :cell-style="cellStyle"
      :page.sync="page"
      @size-change="sizeChange"
      @current-change="currentChange"
      @resetColumn="resetColumn('crud', 'option', 'optionBack', 455)"
      @saveColumn="saveColumn('crud', 'option', 'optionBack', 455)"
    >
      <template slot="menuLeft">
        <slot name="menuLeft"></slot>
      </template>
      <tempalte slot="currentStlAmountRMB" slot-scope="{ row }">
        <el-input-number
          v-if="brfalse"
          v-model="row.currentStlAmountRMB"
          @change="armbChange(row)"
          :controls="false"
          placeholder="请输入 本次签收CNY"
          size="mini"
          style="width: 100%;"
          :disabled="row.currentStlCurCode != 'CNY' || (row.currentStlAmountRMB == 0 && row.currentStlAmountUSD == 0)"
        ></el-input-number>
        <span v-else>{{ row.currentStlAmountRMB }}</span>
      </tempalte>
      <tempalte slot="currentStlAmountUSD" slot-scope="{ row }">
        <el-input-number
          v-if="brfalse"
          v-model="row.currentStlAmountUSD"
          @change="ausdChange(row)"
          :controls="false"
          placeholder="请输入 本次签收USD"
          size="mini"
          style="width: 100%;"
          :disabled="row.currentStlCurCode != 'USD' || (row.currentStlAmountRMB == 0 && row.currentStlAmountUSD == 0)"
        ></el-input-number>
        <span v-else>{{ row.currentStlAmountUSD }}</span>
      </tempalte>
      <template slot="stlAmountDr" slot-scope="{ row }">
        <span v-if="row.dc == 'D'">{{ row.stlAmountDr }}</span>
        <span v-if="row.dc == 'C'">{{ row.stlAmountCr }}</span>
      </template>
      <template slot="stlAmountDrUSD" slot-scope="{ row }">
        <span v-if="row.dc == 'D'">{{ row.stlAmountDrUSD }}</span>
        <span v-if="row.dc == 'C'">{{ row.stlAmountCrUSD }}</span>
      </template>
      <template slot="remarkss" slot-scope="{ row }">
        <el-input style="width: 100%;" v-model="row.remarkss" v-if="brfalse" size="mini" autocomplete="off" clearable placeholder="请输入 备注">
        </el-input>
        <span v-else>{{ row.remarkss }}</span>
      </template>
    </avue-crud>
  </div>
</template>

<script>
import { getWorkDicts } from "@/api/system/dictbiz";
import SearchQuery from "@/components/iosbasic-data/searchquery.vue";
import costDetails from "../assembly/costDetails.vue";
import { getRateList } from "@/api/iosBasicData/rateManagement";
import { feecenterSelectByAccNoList } from "@/api/iosBasicData/finstlbills";

export default {
  components: { SearchQuery, costDetails },
  props: {
    queryData: {
      type: Array,
      default: []
    },
    brfalse: {
      type: Boolean,
      default: true
    },
    handleSelectionData: {
      type: Array,
      default: []
    },
    form: {
      type: Object,
      default: {}
    },
    editSave: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      ifInvoiceData: [], // 是否数据
      invoicelosDara: [], // 发票
      curCodeData: [], // 币种
      option: {},
      optionBack: {
        height: "auto",
        calcHeight: 30,
        menuWidth: 60,
        tip: false,
        menu: false,
        border: true,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        refreshBtn: false,
        index: true,
        selection: true,
        align: "center",
        column: [
          {
            label: "原业务编号",
            prop: "billNo",
            width: 120,
            overHidden: true
          },
          {
            label: "发票号",
            prop: "invoiceNo",
            width: 80,
            overHidden: true
          },
          {
            label: "结算单位",
            prop: "corpCnName",
            width: 120,
            overHidden: true
          },
          {
            label: "MB/L NO",
            prop: "mblno",
            width: 100,
            overHidden: true
          },
          {
            label: "本次签收CNY",
            prop: "currentStlAmountRMB",
            width: 100,
            overHidden: true
          },
          {
            label: "本次签收USD",
            prop: "currentStlAmountUSD",
            width: 100,
            overHidden: true
          },
          {
            label: "币种",
            prop: "currentStlCurCode",
            width: 60,
            overHidden: true
          },
          {
            label: "汇率",
            prop: "currentStlExrate",
            width: 80,
            overHidden: true
          },
          {
            label: "对账",
            prop: "isChecked",
            width: 60,
            overHidden: true,
            type: "select",
            dicData: [
              {
                label: "否",
                value: 0
              },
              {
                label: "是",
                value: 1
              }
            ]
          },
          {
            label: "签收",
            prop: "isSignfor",
            width: 60,
            overHidden: true,
            type: "select",
            dicData: [
              {
                label: "否",
                value: 0
              },
              {
                label: "是",
                value: 1
              }
            ]
          },
          {
            label: "发票状态",
            prop: "isInvoice",
            width: 80,
            type: "select",
            dicData: [
              {
                label: "待开发票",
                value: 1
              },
              {
                label: "确认开票",
                value: 2
              },
              {
                label: "不开发票",
                value: 3
              }
            ],
            overHidden: true
          },
          {
            label: "ETD",
            prop: "etd",
            width: 100,
            overHidden: true
          },
          {
            label: "账单编号",
            prop: "accBillNo",
            width: 100,
            overHidden: true
          },
          {
            label: "签收人",
            prop: "signforName",
            width: 80,
            overHidden: true
          },
          {
            label: "签收日期",
            prop: "signforDate",
            width: 100,
            overHidden: true
          },
          {
            label: "操作人",
            prop: "operatorName",
            width: 80,
            overHidden: true
          },
          {
            label: "BOOKINGNO",
            prop: "bookingNo",
            width: 100,
            overHidden: true
          },
          {
            label: "HB/L NO",
            prop: "hblno",
            width: 100,
            overHidden: true
          },
          {
            label: "船名",
            prop: "vesselCnName",
            width: 80,
            overHidden: true
          },
          {
            label: "航次",
            prop: "voyageNo",
            width: 80,
            overHidden: true
          },
          {
            label: "发票CNY",
            prop: "currentInvoiceAmountRMB",
            width: 80,
            overHidden: true
          },
          {
            label: "发票USD",
            prop: "currentInvoiceAmountUSD",
            width: 80,
            overHidden: true
          },
          {
            label: "箱量",
            prop: "quantityCntrTypesDescr",
            width: 80,
            overHidden: true
          },
          {
            label: "收付",
            prop: "dc",
            width: 60,
            type: "select",
            dicData: [
              {
                label: "收",
                value: "D"
              },
              {
                label: "付",
                value: "C"
              }
            ],
            overHidden: true
          },
          {
            label: "账单CNY",
            prop: "unsettledAmountRMB",
            width: 100,
            overHidden: true
          },
          {
            label: "账单USD",
            prop: "unsettledAmountUSD",
            width: 100,
            overHidden: true
          },
          {
            label: "已签收CNY",
            prop: "reconciliationAmount",
            width: 100,
            overHidden: true
          },
          {
            label: "已签收USD",
            prop: "reconciliationAmountUsd",
            width: 100,
            overHidden: true
          },
          {
            label: "已结算CNY",
            prop: "stlAmountDr",
            width: 90,
            overHidden: true
          },
          {
            label: "已结算USD",
            prop: "stlAmountDrUSD",
            width: 90,
            overHidden: true
          },
          // {
          //     label: "费用名称",
          //     prop: "feeCnName",
          //     width: 80,
          //     overHidden: true
          // },
          {
            label: "业务员",
            prop: "srcCnName",
            width: 80,
            overHidden: true
          },
          {
            label: "备注",
            prop: "remarkss",
            width: 120,
            overHidden: true
          }
        ]
      },
      page: {
        currentPage: 1,
        total: 0,
        pageSize: 20,
        pageSizes: [20, 50, 100, 200, 500]
      },
      pageData: []
    };
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(455), this.optionBack);
    this.isSignforWorkDicts();
    this.invoicelosWorkDictsfun();
  },
  methods: {
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
      this.getList();
    },
    currentChange(val) {
      this.page.currentPage = val;
      this.getList();
    },
    getList() {
      this.page.total = this.queryData.length;
      const start = (this.page.currentPage - 1) * this.page.pageSize;
      const end = start + this.page.pageSize;
      this.pageData = this.queryData.slice(start, end);
    },
    armbChange(row) {
      if (Number(row.amount - row.reconciliationAmount) > 0) {
        if (Number(row.currentStlAmountRMB) < 0) {
          row.currentStlAmountRMB = 0;
          return this.$message.error("本次签收金额不能输入负数");
        }
        if (Number(row.currentStlAmountRMB) > Number(row.amount - row.reconciliationAmount)) {
          row.currentStlAmountRMB = 0;
          return this.$message.error("本次签收金额不能超过未对账金额");
        }
      }
      if (Number(row.amount - row.reconciliationAmount) < 0) {
        if (row.currentStlAmountRMB >= 0) {
          row.currentStlAmountRMB = Number(row.amount - row.reconciliationAmount);
          return this.$message.error("本次签收金额不能输入非负数");
        }
        if (Number(row.currentStlAmountRMB) < Number(row.amount - row.reconciliationAmount)) {
          row.currentStlAmountRMB = Number(row.amount - row.reconciliationAmount);
          return this.$message.error("本次签收金额不能超过未对账金额");
        }
      }
    },
    ausdChange(row) {
      if (Number(row.amount - row.reconciliationAmount) > 0) {
        if (Number(row.currentStlAmountUSD) < 0) {
          row.currentStlAmountUSD = 0;
          return this.$message.error("本次签收金额不能输入负数");
        }
        if (Number(row.currentStlAmountUSD) > Number(row.amount - row.reconciliationAmount)) {
          row.currentStlAmountUSD = 0;
          return this.$message.error("本次签收金额不能超过未对账金额");
        }
      }
      if (Number(row.amount - row.reconciliationAmount) < 0) {
        if (row.currentStlAmountUSD >= 0) {
          row.currentStlAmountUSD = Number(row.amount - row.reconciliationAmount);
          return this.$message.error("本次签收金额不能输入非负数");
        }
        if (Number(row.currentStlAmountUSD) < Number(row.amount - row.reconciliationAmount)) {
          row.currentStlAmountUSD = Number(row.amount - row.reconciliationAmount);
          return this.$message.error("本次签收金额不能超过未对账金额");
        }
      }
    },
    // 币别选择监听
    corpChange(value, row) {
      for (let item of this.curCodeData) {
        if (item.code == value) {
          this.$set(row, "currentStlCurCode", value);
          if (value == "CNY") {
            delete row.currentStlAmountUSD;
            this.$set(row, "currentStlAmountRMB", row.unsettledAmount);
          } else {
            delete row.currentStlAmountRMB;
            this.$set(row, "currentStlAmountUSD", row.unsettledAmount);
          }
        }
      }
    },
    // 展开行或者关闭
    expandChange(row, expandedRows) {
      let accBillId = "";
      if (this.form.id) {
        accBillId = row.accBillId;
      } else {
        accBillId = row.id;
      }
      feecenterSelectByAccNoList({ accBillId }).then(res => {
        row.costDate = res.data.data.map(item => {
          if (item.curCode == "CNY") {
            this.$set(item, "rmbAmount", item.amount);
            this.$set(item, "usdAmount", "");
            this.$set(item, "rmbAmountNet", item.amountNet);
            this.$set(item, "usdAmountNet", "");
          } else {
            this.$set(item, "usdAmount", item.amount);
            this.$set(item, "rmbAmount", "");
            this.$set(item, "usdAmountNet", item.amountNet);
            this.$set(item, "rmbAmountNet", "");
          }
          return item;
        });
      });
    },
    // 接口请求
    // 是否接口
    isSignforWorkDicts() {
      getWorkDicts("ifInvoice").then(res => {
        this.ifInvoiceData = res.data.data;
      });
    },
    // 发票
    invoicelosWorkDictsfun() {
      getWorkDicts("reconciliation_invoice_los").then(res => {
        this.invoicelosDara = res.data.data;
      });
    },
    // 获取币别数据
    getRateListfun(cnName) {
      getRateList({ current: 1, size: 10, cnName }).then(res => {
        this.curCodeData = res.data.data.records;
      });
    },

    // 表头样式
    tableHeaderCellStyle({ row, column, rowIndex, columnIndex }) {
      return "padding:4px 0px;fontSize:12px;color:#000;background:#ecf5ff";
    },

    // Element UI 表格点击选中行/取消选中 快捷多选 以及快捷连续多选，高亮选中行 ——-------------------------------------——
    // 多选选择的数据
    handleSelectionChange(arr) {
      // // 全选
      // if (arr.length == this.queryData.length) {
      //     for (let item of arr) {
      //         this.$set(item,'tableSelect',1)
      //     }
      // }
      // // 清除全选
      // if (arr.length == 0) {
      //     for (let item of this.queryData) {
      //         this.$set(item,'tableSelect',0)
      //     }
      // }
      this.$emit("handleSelectionChange", arr);
    },
    // // 多选
    // toggleSelection(rows){
    //     if (rows) {
    //         rows.forEach(row => {
    //             this.$refs.tableRef.toggleRowSelection(row);
    //         });
    //     } else {
    //         this.$refs.tableRef.clearSelection();
    //     }
    // },
    // 监听点击表格事件
    rowClick(row, column, event) {
      let refsElTable = this.$refs.tableRef; // 获取表格对象
      if (this.CtrlDown) {
        refsElTable.toggleRowSelection(row); // ctrl多选 如果点击两次同样会取消选中
        return;
      }
      if (this.shiftOrAltDown && this.handleSelectionData.length > 0) {
        // 通过rowIndex判断已选择的行中最上面和最下面的是哪行，再对比按住shift/alt点击的当前行得到新的最上面和最下面的行，把这两行中间的行进行循环选中。
        let topAndBottom = this.getTopAndBottom(row, this.bottomSelectionRow, this.topSelectionRow);
        refsElTable.clearSelection(); //先清空 不然会导致在这两行中间之外的行状态不变
        for (let index = topAndBottom.top; index <= topAndBottom.bottom; index++) {
          //选中两行之间的所有行
          refsElTable.toggleRowSelection(this.queryData[index], true);
        }
      } else {
        let findRow = this.handleSelectionData.find(c => c.rowIndex == row.rowIndex); //找出当前选中行
        //如果只有一行且点击的也是这一行则取消选择 否则清空再选中当前点击行
        if (findRow && this.handleSelectionData.length === 1) {
          refsElTable.toggleRowSelection(row, false);
          return;
        }
        // refsElTable.clearSelection(); // 清空之前选择的数据(如果放开，选择之前会变成单选)
        refsElTable.toggleRowSelection(row); // 调用选中行方法
      }
    },
    // 行的 style 的回调方法
    rowStyle({ row, rowIndex }) {
      // 直接在一个对象上定义一个新属性，或者修改一个对象的现有属性，并返回此对象
      // object: 要添加或者修改属性的目标对象；prop: 要定义或修改属性的名称；descript: 是一个对象，里面是我们上述的对象属性的特性；
      Object.defineProperty(row, "rowIndex", {
        //给每一行添加不可枚举属性rowIndex来标识当前行
        value: rowIndex, // 设置age的值，不设置的话默认为undefined
        writable: true, // 表示属性的值true可以修改,false不可以被修改
        enumerable: false // 设置为false表示不能通过 for-in 循环返回
        // configurable: false, // configurable 设置为 false，意味着这个属性不能从对象上删除
      });
    },
    keyDown(event) {
      let key = event.keyCode;
      if (key == 17) this.CtrlDown = true;
      if (key == 16 || key == 18) this.shiftOrAltDown = true;
    },
    keyUp(event) {
      let key = event.keyCode;
      if (key == 17) this.CtrlDown = false;
      if (key == 16 || key == 18) this.shiftOrAltDown = false;
    },
    // 文章说明 https://www.jianshu.com/p/48f2c522d2a2
    getTopAndBottom(row, bottom, top) {
      let n = row.rowIndex,
        mx = bottom.rowIndex,
        mi = top.rowIndex;
      if (n > mx) {
        return {
          top: mi,
          bottom: n
        };
      } else if (n < mx && n > mi) {
        return {
          top: mi,
          bottom: n
        };
      } else if (n < mi) {
        return {
          top: n,
          bottom: mx
        };
      } else if (n == mi || n == mx) {
        return {
          top: mi,
          bottom: mx
        };
      }
    },
    // 给选中行加上current-row这个class类，所以要使用row-class-name这个属性（其实给每一行添加rowIndex也可以用这个属性），
    // 判断方式也是通过判断rowIndex对比
    rowClassName({ row, rowIndex }) {
      let rowName = "",
        findRow = this.handleSelectionData.find(c => {
          return c.rowIndex === row.rowIndex;
        });
      if (findRow) {
        rowName = "current-row "; // elementUI 默认高亮行的class类 不用再样式了^-^,也可通过css覆盖改变背景颜色
      }
      return rowName; //也可以再加上其他类名 如果有需求的话
    },
    // 收付展示不一样的颜色
    cellStyle({ row, rowIndex, columnIndex }) {
      let rowStyle = "";
      if (row.dc == "D") {
        rowStyle = "color:#F56C6C;";
      } else if (row.dc == "C") {
        rowStyle = "color:#67C23A;";
      }
      return rowStyle + "padding:0px;fontSize:12px";
    },
    //自定义列保存
    async saveColumn(ref, option, optionBack, code) {
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumn(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    }
  },
  mounted() {
    // 按住ctrl实现多选 设置监听keydown事件,以及keyup事件，
    addEventListener("keydown", this.keyDown, false);
    addEventListener("keyup", this.keyUp, false);
  },
  beforeDestroy() {
    //解绑
    removeEventListener("keydown", this.keyDown);
    removeEventListener("keyup", this.keyUp);
  },
  watch: {
    queryData: {
      // 执行方法
      handler(oldValue, newValue) {
        this.page.currentPage = 1;
        this.pageData = [];
        this.getList();
      },
      deep: true, // 深度监听
      immediate: true // 第一次改变就执行
    }
  },
  computed: {
    //实时得到最上行和最下行
    bottomSelectionRow() {
      if (this.handleSelectionData.length == 0) return null;
      return this.handleSelectionData.reduce((start, end) => {
        return start.rowIndex > end.rowIndex ? start : end;
      });
    },
    topSelectionRow() {
      if (this.handleSelectionData.length == 0) return null;
      return this.handleSelectionData.reduce((start, end) => {
        return start.rowIndex < end.rowIndex ? start : end;
      });
    }
  }
};
</script>

<style scoped>
.textHide {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

::v-deep .current-row {
  background: #ecf3ff;
}
</style>
