<template>
  <div>
    <el-dialog title="指示" :visible.sync="dialogVisible" append-to-body width="60%" :before-close="handleClose">
      <el-tag type="success" style="margin-right: 10px;">剩余收费(RMB){{ Number(form.amountDr - form.actualAmountDr).toFixed(2) }}</el-tag>
      <el-tag type="info" style="margin-right: 10px;">剩余收费(USD){{ Number(form.amountDrUsd - form.actualAmountDrUsd).toFixed(2) }}</el-tag>
      <el-tag type="warning" style="margin-right: 10px;">剩余付费(RMB){{ Number(form.amountCr - form.actualAmountCr).toFixed(2) }}</el-tag>
      <el-tag type="danger">剩余付费(USD){{ Number(form.amountCrUsd - form.actualAmountCrUsd).toFixed(2) }}</el-tag>
      <avue-crud
        v-if="dialogVisible"
        :option="option"
        :table-loading="loading"
        :data="data"
        ref="crud"
        id="out-table"
        :header-cell-class-name="headerClassName"
        @on-load="onLoad"
      >
        <template slot="indexHeader" slot-scope="{ row }">
          <el-button type="primary" size="small" icon="el-icon-plus" circle @click="addRow"></el-button>
        </template>
        <template slot="index" slot-scope="{ row, index }">
          <span>{{ index + 1 }}</span>
        </template>
        <template slot="status" slot-scope="{ row }">
          <span v-if="row.status == 0">{{ row.dc == "D" ? "未收款" : "未支付" }}</span>
          <span v-if="row.status == 1">{{ row.dc == "D" ? "已收款" : "已支付" }}</span>
          <span v-if="row.status == 2">{{ row.dc == "D" ? "部分收款" : "部分支付" }}</span>
        </template>
        <template slot="curCode" slot-scope="{ row }">
          <dic-select
            v-if="row.$cellEdit"
            :key="row.dc"
            v-model="row.curCode"
            placeholder="币别"
            label="code"
            :url="'/blade-los/bcurrency/getExrate?type=2&date=' + form.billDate + ' 00:00:00' + '&dc=' + row.dc"
            :filterable="true"
            @selectChange="rowDicChange('curCode', $event, row)"
          ></dic-select>
          <span v-else>{{ row.curCode }}</span>
        </template>
        <template slot="exrate" slot-scope="{ row }">
          <el-input-number
            v-if="row.$cellEdit"
            style="width: 100%;"
            v-model="row.exrate"
            @change="calculateChange(row)"
            label="请输入汇率"
            size="small"
            :controls="false"
          ></el-input-number>
          <span v-else>{{ row.exrate }}</span>
        </template>
        <!-- <template slot="amount" slot-scope="{ row }">
          <el-input-number
            v-if="row.$cellEdit"
            style="width: 100%;"
            v-model="row.amount"
            @change="calculateChange(row)"
            label="请输入金额"
            size="small"
            :controls="false"
          ></el-input-number>
          <span v-else>{{ row.amount }}</span>
        </template> -->
        <template slot="dc" slot-scope="{ row }">
          <el-select v-if="row.$cellEdit" v-model="row.dc" placeholder="请选择" size="small" @change="dcChange(row)">
            <el-option v-for="item in dcOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
          <span v-else>{{ row.dc == "D" ? "收" : "付" }}</span>
        </template>
        <template slot="taxRate" slot-scope="{ row }">
          <el-input-number
            v-if="row.$cellEdit"
            style="width: 100%;"
            v-model="row.taxRate"
            @change="calculateChange(row)"
            label="请输入税率"
            size="small"
            :controls="false"
            :min="0"
          ></el-input-number>
          <span v-else>{{ row.taxRate }}</span>
        </template>
        <template slot="menu" slot-scope="{ row, index }">
          <el-button type="text" size="small" @click="rowEdit(row)" :disabled="row.status == 1">{{ row.$cellEdit ? "保存" : "编辑" }}</el-button>
          <el-button type="text" size="small" @click="rowDel(row, index)" :disabled="row.status == 1">删除</el-button>
        </template>
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button v-if="form.cashierStatus == 0" size="mini" type="success" :disabled="data.length == 0" @click="allClick('申请出纳')"
          >付费申请</el-button
        >
        <el-button v-if="form.cashierStatus == 1" size="mini" type="danger" @click="allClick('撤销申请出纳')">撤销付费申请</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { MktSlotQuotation, quotationImportBatch } from "@/api/iosBasicData/bills";
import dicSelect from "@/components/dicSelect/main";
import { getListAll, submit, submitList, remove, applyCashier, revokeCashier } from "@/api/iosBasicData/cashier.js";
import { bcurrencyGetExrate } from "@/api/iosBasicData/rateManagement";
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    }
  },
  components: { dicSelect },
  data() {
    return {
      form: {},
      data: [],
      options: [
        {
          value: 0,
          label: "不含税"
        },
        {
          value: 1,
          label: "含税"
        }
      ],
      dcOptions: [
        {
          value: "D",
          label: "收"
        },
        {
          value: "C",
          label: "付"
        }
      ],
      dialogVisible: false,
      loading: false,
      option: {
        height: 500,
        calcHeight: 30,
        border: true,
        // index: true,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        // menu: false,
        menuWidth: 100,
        header: false,
        align: "center",
        column: [
          {
            label: "index",
            prop: "index",
            width: "55",
            headerslot: true
          },
          {
            label: "状态",
            prop: "status",
            width: "60",
            overHidden: true
          },
          {
            label: "收/付",
            prop: "dc",
            width: "90",
            overHidden: true
          },
          {
            label: "币别",
            prop: "curCode",
            width: "100",
            overHidden: true
          },
          {
            label: "汇率",
            prop: "exrate",
            width: "70",
            overHidden: true
          },
          {
            label: "金额",
            prop: "amount",
            width: "100",
            overHidden: true
          },
          {
            label: "转汇后金额",
            prop: "amountLoc",
            width: "100",
            overHidden: true
          },
          {
            label: "税率(%)",
            prop: "taxRate",
            width: "80",
            overHidden: true
          },
          {
            label: "净额",
            prop: "amountNet",
            width: "100",
            overHidden: true
          },
          {
            label: "税额",
            prop: "amountTax",
            width: "80",
            overHidden: true
          },
          {
            label: "经办人",
            prop: "cashierName",
            width: "100",
            overHidden: true
          },
          {
            label: "经办时间",
            prop: "cashierTime",
            width: "100",
            overHidden: true
          },
          {
            label: "创建人",
            prop: "createUserName",
            width: "100",
            overHidden: true
          },
          {
            label: "创建时间",
            prop: "createTime",
            width: "100",
            overHidden: true
          },
          {
            label: "备注",
            prop: "remarks",
            cell: true,
            width: 120,
            overHidden: true
          }
        ]
      }
    };
  },
  async created() {
    // this.option = await this.getColumnData(this.getColumnName(309.6), this.optionBack);
  },
  methods: {
    async oneClickGeneration(row, list, dataList) {
      if (list.length == 0) {
        this.processData(row, list, dataList);
      }
      if (list.length) {
        let ids = [];
        for (const item of list) {
          ids.push(item.id);
        }
        await remove({ ids: ids.join(",") });
        this.data = [];
        this.processData(row, list, dataList);
      }
    },
    //生成指示
    async processData(row, list, dataList) {
      let amountDr = 0;
      let amountDrUsd = 0;
      let amountCr = 0;
      let amountCrUsd = 0;
      for (let item of dataList) {
        if (item.dc == "D" && item.currentStlCurCode == "CNY") {
          amountDr += Number(item.currentStlAmountRMB);
        }
        if (item.dc == "D" && item.currentStlCurCode == "USD") {
          amountDrUsd += Number(item.currentStlAmountUSD);
        }
        if (item.dc == "C" && item.currentStlCurCode == "CNY") {
          amountCr += Number(item.currentStlAmountRMB);
        }
        if (item.dc == "C" && item.currentStlCurCode == "USD") {
          amountCrUsd += Number(item.currentStlAmountUSD);
        }
      }
      if (amountDr > 0 || amountDrUsd > 0) {
        let obj = {
          type: 2,
          date: row.billDate + " 00:00:00",
          dc: "D"
        };
        const res = await bcurrencyGetExrate(obj);
        res.data.data.forEach(item => {
          if (amountDr > 0 && item.code == "CNY") {
            this.data.push({
              srcId: row.id,
              dc: "D",
              curCode: item.code,
              exrate: item.exrate,
              amount: amountDr,
              amountLoc: Number(Number(amountDr ? amountDr : 0)).toFixed(2),
              taxRate: 0,
              amountTax: Number(Number(amountDr ? amountDr : 0)).toFixed(2),
              amountNet: 0,
              applyCashierAmount: 0
            });
          }
          if (amountDrUsd > 0 && item.code == "USD") {
            this.data.push({
              srcId: row.id,
              dc: "D",
              curCode: item.code,
              exrate: item.exrate,
              amount: amountDrUsd,
              amountLoc: Number(Number(amountDrUsd ? amountDrUsd : 0) * Number(item.exrate ? item.exrate : 0)).toFixed(2),
              taxRate: 0,
              amountTax: Number(Number(amountDrUsd ? amountDrUsd : 0) * Number(item.exrate ? item.exrate : 0)).toFixed(2),
              amountNet: 0,
              applyCashierAmount: 0
            });
          }
        });
      }
      if (amountCr > 0 || amountCrUsd > 0) {
        let obj = {
          type: 2,
          date: row.billDate + " 00:00:00",
          dc: "C"
        };
        const res = await bcurrencyGetExrate(obj);
        res.data.data.forEach(item => {
          if (amountCr > 0 && item.code == "CNY") {
            this.data.push({
              srcId: row.id,
              dc: "C",
              curCode: item.code,
              exrate: item.exrate,
              amount: amountCr,
              amountLoc: Number(Number(amountCr ? amountCr : 0)).toFixed(2),
              taxRate: 0,
              amountTax: Number(Number(amountCr ? amountCr : 0)).toFixed(2),
              amountNet: 0,
              applyCashierAmount: 0
            });
          }
          if (amountCrUsd > 0 && item.code == "USD") {
            this.data.push({
              srcId: row.id,
              dc: "C",
              curCode: item.code,
              exrate: item.exrate,
              amount: amountCrUsd,
              amountLoc: Number(Number(amountCrUsd ? amountCrUsd : 0) * Number(item.exrate ? item.exrate : 0)).toFixed(2),
              taxRate: 0,
              amountTax: Number(Number(amountCrUsd ? amountCrUsd : 0) * Number(item.exrate ? item.exrate : 0)).toFixed(2),
              amountNet: 0,
              applyCashierAmount: 0
            });
          }
        });
      }
      if (this.data.length) {
        const res = await submitList(this.data);
        this.data = res.data.data;
      }
    },
    rowEdit(row) {
      if (row.$cellEdit) {
        if (!row.curCode) {
          return this.$message.error("币别不能为空");
        }
        if (!row.exrate) {
          return this.$message.error("汇率不能为空");
        }
        if (!row.amount || row.amount == 0 || row.amount < 0) {
          return this.$message.error("金额不能为非正数");
        }
        if (row.dc == "D" && row.curCode == "CNY") {
          if (Number(row.amount) > Number(this.form.amountDr - this.form.actualAmountDr)) {
            return this.$message.error("金额不能超过剩余出纳收费(RMB):" + Number(this.form.amountDr - this.form.actualAmountDr));
          }
        }
        if (row.dc == "D" && row.curCode == "USD") {
          if (Number(row.amount) > Number(this.form.amountDrUsd - this.form.actualAmountDrUsd)) {
            return this.$message.error("金额不能超过剩余出纳收费(USD):" + Number(this.form.amountDrUsd - this.form.actualAmountDrUsd));
          }
        }
        if (row.dc == "C" && row.curCode == "CNY") {
          if (Number(row.amount) > Number(this.form.amountCr - this.form.actualAmountCr)) {
            return this.$message.error("金额不能超过剩余出纳付费(RMB):" + Number(this.form.amountCr - this.form.actualAmountCr));
          }
        }
        if (row.dc == "C" && row.curCode == "USD") {
          if (Number(row.amount) > Number(this.form.amountCrUsd - this.form.actualAmountCrUsd)) {
            return this.$message.error("金额不能超过剩余出纳付费(USD):" + Number(this.form.amountCrUsd - this.form.actualAmountCrUsd));
          }
        }
        submit(row).then(res => {
          this.$set(row, "$cellEdit", false);
          this.$message({
            type: "success",
            message: "保存成功!"
          });
          for (let [key, value] of Object.entries(res.data.data)) {
            this.$set(row, key, value);
          }
        });
      } else {
        this.$set(row, "$cellEdit", true);
      }
    },
    allClick(name) {
      if (name == "申请出纳") {
        for (let item of this.data) {
          if (!item.id || item.$cellEdit) {
            return this.$message.error("请保存数据");
          }
        }
        const loading = this.$loading({
          lock: true,
          text: "加载中",
          spinner: "el-icon-loading",
          background: "rgba(255,255,255,0.7)"
        });
        applyCashier({ id: this.form.id })
          .then(res => {
            this.$emit("update");
          })
          .finally(() => {
            loading.close();
          });
      }
      if (name == "撤销申请出纳") {
        for (let item of this.data) {
          if (!item.id || item.$cellEdit) {
            return this.$message.error("请保存数据");
          }
          if (item.status == 1) {
            return this.$message.error("数据已支付,不允许撤销申请付费");
          }
        }
        this.$confirm("是否撤销申请付费?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: "加载中",
            spinner: "el-icon-loading",
            background: "rgba(255,255,255,0.7)"
          });
          revokeCashier({ id: this.form.id })
            .then(res => {
              this.$emit("update");
            })
            .finally(() => {
              loading.close();
            });
        });
      }
    },
    rowDel(row, index) {
      if (row.id) {
        this.$confirm("确定删除数据?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          remove({ ids: row.id }).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.data.splice(index, 1);
          });
        });
      } else {
        this.data.splice(index, 1);
      }
    },
    calculateChange(row) {
      row.amountLoc = Number(Number(row.amount ? row.amount : 0) * Number(row.exrate ? row.exrate : 0)).toFixed(2);
      row.amountTax = Number(Number(row.amountLoc ? row.amountLoc : 0) * Number(row.taxRate ? row.taxRate / 100 : 0)).toFixed(2);
      row.amountNet = Number(Number(row.amountLoc ? row.amountLoc : 0) - Number(row.amountTax ? row.amountTax : 0)).toFixed(2);
    },
    dcChange(row) {
      row.curCode = null;
      row.exrate = null;
      this.calculateChange(row);
    },
    rowDicChange(name, row, el) {
      if (name == "curCode") {
        if (row) {
          el.exrate = row.exrate;
          if (el.dc == "D" && el.curCode == "CNY") {
            if (this.data.filter(item => el.dc == item.dc && el.curCode == item.curCode).length == 1) {
              el.amount = Number(this.form.amountDr - this.form.actualAmountDr).toFixed(2);
            }
            if (this.data.filter(item => el.dc == item.dc && el.curCode == item.curCode).length == 2) {
              el.amount = Number(0).toFixed(2);
            }
          }
          if (el.dc == "D" && el.curCode == "USD") {
            if (this.data.filter(item => el.dc == item.dc && el.curCode == item.curCode).length == 1) {
              el.amount = Number(this.form.amountDrUsd - this.form.actualAmountDrUsd).toFixed(2);
            }
            if (this.data.filter(item => el.dc == item.dc && el.curCode == item.curCode).length == 2) {
              el.amount = Number(0).toFixed(2);
            }
          }
          if (el.dc == "C" && el.curCode == "CNY") {
            if (this.data.filter(item => el.dc == item.dc && el.curCode == item.curCode).length == 1) {
              el.amount = Number(this.form.amountCr - this.form.actualAmountCr).toFixed(2);
            }
            if (this.data.filter(item => el.dc == item.dc && el.curCode == item.curCode).length == 2) {
              el.amount = Number(0).toFixed(2);
            }
          }
          if (el.dc == "C" && el.curCode == "USD") {
            if (this.data.filter(item => el.dc == item.dc && el.curCode == item.curCode).length == 1) {
              el.amount = Number(this.form.amountCrUsd - this.form.actualAmountCrUsd).toFixed(2);
            }
            if (this.data.filter(item => el.dc == item.dc && el.curCode == item.curCode).length == 2) {
              el.amount = Number(0).toFixed(2);
            }
          }
          this.calculateChange(el);
        } else {
          el.exrate = null;
          this.calculateChange(el);
        }
      }
    },
    addRow() {
      this.data.push({ $cellEdit: true, srcId: this.form.id, dc: this.form.dc, taxRate: 0 });
    },
    openDialog(row, dataList, type) {
      this.dialogVisible = true;
      this.form = row;
      let obj = {
        srcId: row.id
      };
      this.loading = true;
      getListAll(obj)
        .then(res => {
          if (row.cashierStatus == 0 && type == "auto") {
            this.oneClickGeneration(row, res.data.data, dataList);
          }
          this.data = res.data.data;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //自定义列保存
    async saveColumn(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
        this.searchReset();
      }
    },
    //自定义列重置
    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;
      }
    },

    // 更改表格颜色
    headerClassName(tab) {
      //颜色间隔
      let back = "";
      if (tab.columnIndex >= 0 && tab.column.level === 1) {
        if (tab.columnIndex % 2 === 0) {
          back = "back-one";
        } else if (tab.columnIndex % 2 === 1) {
          back = "back-two";
        }
      }
      return back;
    }
  }
};
</script>

<style scoped>
::v-deep#out-table .back-one {
  background: #ecf5ff !important;
  text-align: center;
  padding: 4px 0;
}

::v-deep#out-table .back-two {
  background: #ecf5ff !important;
  text-align: center;
  padding: 4px 0;
}
</style>
