<template>
  <div v-if="showDetail">
    <div style="display: flex; justify-content: space-between">
      <div style="display: flex; align-items: center">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item
            ><span style="font-weight: 700">对账</span></el-breadcrumb-item
          >
          <el-breadcrumb-item
            ><span style="font-weight: 700"
              >对账详情页</span
            ></el-breadcrumb-item
          >
        </el-breadcrumb>
        <el-button
          style="margin-left: 10px"
          size="mini"
          icon="el-icon-arrow-left"
          @click="cancel"
          >返回列表
        </el-button>
      </div>
      <!-- <div v-if="showApproval == 0">
       审核
      </div> -->
    </div>
    <br />
    <el-form ref="form" :model="form" label-width="80px">
      <el-row>
        <el-col :span="6">
          <el-form-item
            label="客户名称"
            prop="fCorpid"
          >
            <el-select
              v-model="form.fCorpid"
              size="small"
              placeholder="请选择"
              clearable
              :disabled="
                form.fBillstatus >= 4 || readOnly == 0 || tableData.length > 0
              "
              style="width: 100%"
            >
              <el-option
                v-for="item in corpList"
                :key="item.fId"
                :label="item.fName"
                :value="item.fId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开船日期">
            <el-date-picker
              v-model="form.date"
              type="daterange"
              size="small"
              placeholder="请选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :disabled="form.fBillstatus >= 4 || readOnly == 0"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="船名">
            <el-select
              v-model="form.fVslid"
              size="small"
              placeholder="请选择"
              clearable
              :disabled="form.fBillstatus >= 4 || readOnly == 0"
              style="width: 100%"
            >
              <el-option
                v-for="item in TVesselfs"
                :key="item.fId"
                :label="item.fName"
                :value="item.fId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="航次">
            <el-select
              v-model="form.fVoyid"
              size="small"
              placeholder="请选择"
              clearable
              :disabled="form.fBillstatus >= 4 || readOnly == 0"
              style="width: 100%"
            >
              <el-option
                v-for="item in TVoyagefs"
                :key="item.fId"
                :label="item.fNo"
                :value="item.fId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="提单号">
            <el-input
              v-model="form.tMblno"
              size="small"
              placeholder="请输入"
              :disabled="form.fBillstatus >= 4 || readOnly == 0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="起运港">
            <el-select
              v-model="form.fLoadportid"
              size="small"
              placeholder="请选择"
              clearable
              :disabled="form.fBillstatus >= 4 || readOnly == 0"
              style="width: 100%"
            >
              <el-option
                v-for="item in portNames"
                :key="item.fId"
                :label="item.fName"
                :value="item.fId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="目的港">
            <el-select
              v-model="form.fDestportid"
              size="small"
              placeholder="请选择"
              clearable
              :disabled="form.fBillstatus >= 4 || readOnly == 0"
              style="width: 100%"
            >
              <el-option
                v-for="item in portNames"
                :key="item.fId"
                :label="item.fName"
                :value="item.fId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否对账" prop="fReconciliation">
            <el-select
              v-model="form.fReconciliation"
              size="small"
              clearable
              :disabled="form.fBillstatus >= 4 || readOnly == 0"
              style="width: 100%"
            >
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="应收应付" prop="fDc">
            <el-select
              v-model="form.fDc"
              size="small"
              clearable
              :disabled="form.fBillstatus >= 4 || readOnly == 0"
              style="width: 100%"
            >
              <el-option label="应收" value="D" />
              <el-option label="应付" value="C" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="系统编号">
            <el-input
              v-model="form.srcBillNo"
              size="small"
              placeholder="请输入"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="制单人">
            <el-input
              v-model="form.createBy"
              size="small"
              placeholder="请输入"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="制单日期">
            <el-date-picker
              v-model="form.createTime"
              size="small"
              placeholder="请选择"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd 00:00:00"
              disabled
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注">
            <el-input
              type="textarea"
              v-model="form.fRemarks"
              size="small"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开票备注">
            <el-input
              type="textarea"
              v-model="form.invoiceRemarks"
              size="small"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="head-but">
      <div>
        <el-button
          type="primary"
          size="mini"
          @click="submit"
          :disabled="form.fBillstatus >= 4 || readOnly == 0"
        >
          确认对账
        </el-button>
        <el-button
          type="success"
          size="mini"
          @click="backrRconciliation"
          v-if="form.fBillstatus === '6'"
          >撤销对账</el-button
        >
        <el-button
          type="danger"
          size="mini"
          v-if="form.fBillstatus == 4"
          @click="backApproval('f_billstatus')"
          >撤销审批</el-button
        >
        <el-button
          v-if="readOnly == 3"
          size="mini"
          @click="goApproval('f_billstatus')"
          >审批</el-button
        >
        <el-button
          type="primary"
          size="mini"
          v-if="form.fBillstatus >= '3'"
          @click="addOrUpdateHandle('f_billstatus')"
          >查看审批流</el-button
        >
        <el-button type="success" size="mini" @click="save"> 保存 </el-button>
        <el-button
          type="warning"
          size="mini"
          :disabled="!form.fId"
          @click="handleExport"
        >
          导出
        </el-button>
        <el-button
          type="cyan"
          icon="el-icon-search"
          size="mini"
          @click="Search"
          :disabled="form.fBillstatus >= 4 || readOnly == 0"
        >
          检索
        </el-button>
      </div>
      <div class="tabSetting">
        <div style="margin: 0 12px">
          <el-button
            icon="el-icon-setting"
            size="mini"
            circle
            @click="colSetting"
          ></el-button>
        </div>
      </div>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column
        v-for="(item, index) in tableOption"
        :key="index"
        :label="item.name"
        :width="item.width"
        :prop="item.label"
        align="center"
        :fixed="item.fixed"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span v-if="item.label == 'srcBillNo'">
            {{ scope.row.srcBillNo }}
          </span>
          <span v-if="item.label == 'fName'">
            {{ scope.row.fName }}
          </span>
          <span v-if="item.label == 'fFeeName'">
            {{ scope.row.fFeeName }}
          </span>
          <span v-if="item.label == 'goodName'">
            {{ scope.row.goodName }}
          </span>
          <span v-if="item.label == 'fFeeUnitName'">
            {{ scope.row.fFeeUnitName }}
          </span>
          <span v-if="item.label == 'fQty'">
            {{ scope.row.fQty }}
          </span>
          <span v-if="item.label == 'fUnitPrice'">
            {{ scope.row.fUnitPrice }}
          </span>
          <span v-if="item.label == 'fAmtdr'">
            {{ scope.row.fAmtdr }}
          </span>
          <span v-if="item.label == 'fAmt'">
            <el-input
              v-model="scope.row.fAmt"
              size="small"
              placeholder="请输入"
              :disabled="form.fBillstatus >= 4 || readOnly == 0"
              @change="fAmtChange(scope.row)"
            ></el-input>
          </span>
          <span v-if="item.label == 'fvslName'">
            {{ scope.row.fvslName }}
          </span>
          <span v-if="item.label == 'fvoyName'">
            {{ scope.row.fvoyName }}
          </span>
          <span v-if="item.label == 'fCntrCount'">
            {{ scope.row.fCntrCount }}
          </span>
          <span v-if="item.label == 'cntrName'">
            {{ scope.row.cntrName }}
          </span>
          <span v-if="item.label == 'fLoadPortName'">
            {{ scope.row.fLoadPortName }}
          </span>
          <span v-if="item.label == 'fDestPortName'">
            {{ scope.row.fDestPortName }}
          </span>
          <span v-if="item.label == 'fBillStatusName'">
            {{ scope.row.fBillStatusName }}
          </span>
          <span v-if="item.label == 'createBy'">
            {{ scope.row.createBy }}
          </span>
          <span v-if="item.label == 'createTime'">
            {{ scope.row.createTime }}
          </span>
          <span v-if="item.label == 'fRemarks'">
            <el-input
              v-model="scope.row.fRemarks"
              size="small"
              placeholder="请输入"
              :disabled="form.fBillstatus >= 4 || readOnly == 0"
            ></el-input>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="rowDel(scope.row, scope.$index, tableData)"
            :disabled="form.fBillstatus >= 4 || readOnly == 0"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <approval-comments
      v-if="addOrUpdateVisib"
      ref="ApprovalComments"
      @refreshDataList="returnData"
    />
    <add-or-update ref="addOrUpdate" @imporData="imporData" />
    <view-approval ref="viewApproval" />
    <column-setting
      ref="columnSetting"
      @reset="reset"
      @getRowdata="getRowdata"
      tableName="凯和对账详情页"
    />
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { tableOption2 } from "./js/index";
import {
  selectTVesself,
  selectTVoyagef,
  selectPortName,
  save,
  listCorps,
  confirm,
  RevocationApproval,
  getdetail,
  infoRemove,
  revoke,
  getExcelInfo,
} from "@/api/finance/kaihe/contrast";
import ApprovalComments from "@/views/startApproval";
import addOrUpdate from "./add-or-update.vue";
import viewApproval from "@/views/viewApproval";
import columnSetting from "@/components/ColumnSetting/index";
import _ from "lodash";
export default {
  data() {
    return {
      form: {
        fReconciliation: "0",
        fDc: "D",
        fSystemType: Cookies.get("sysType"),
      },
      options: [],
      tableData: [],
      tableOption: tableOption2,
      TVesselfs: [],
      TVoyagefs: [],
      portNames: [],
      corpList: [],
      wRtions: [],
      approve: false,
      addOrUpdateVisib: false,
      readOnly: null,
    };
  },
  components: {
    ApprovalComments,
    addOrUpdate,
    viewApproval,
    columnSetting,
  },
  props: {
    showDetail: {
      type: Boolean,
    },
  },
  created() {},
  methods: {
    /** 导出按钮操作 */
    handleExport() {
      let _this = this;
      this.$confirm("是否确认导出明细数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return getExcelInfo(_this.form.fId);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    getRowdata(list) {
      this.tableOption = list;
    },
    reset() {
      this.tableOption = this.$options.data().tableOption;
    },
    colSetting() {
      this.$refs.columnSetting.init(this.tableOption);
    },
    init() {
      selectTVesself().then((res) => {
        this.TVesselfs = res.rows;
      });
      selectTVoyagef().then((res) => {
        this.TVoyagefs = res.rows;
      });
      selectPortName().then((res) => {
        this.portNames = res.rows;
      });
      this.getDicts("whether_reconciliation").then((response) => {
        if (response.data) {
          this.wRtions = response.data;
        }
      });
      listCorps().then((res) => {
        this.corpList = res;
      });
      setTimeout((e) => {
        this.$refs.columnSetting.getRow(this.tableOption);
      }, 100);
    },
    fAmtChange(row) {
      if (Number(row.fAmt) > Number(row.fAmtdr)) {
        row.fAmt = row.fAmtdr;
        this.$message.error("实收金额不能超过应收金额");
      }
      if (Number(row.fAmt) <= 0) {
        row.fAmt = row.fAmtdr;
        this.$message.error("请正确输入金额");
      }
    },
    rowDel(row, index, rows) {
      console.log();
      if (row.fId) {
        infoRemove(row.fId).then((res) => {
          if (res.code == 200) {
            rows.splice(index, 1);
            this.$message.success("删除成功");
          }
        });
      } else {
        rows.splice(index, 1);
        this.$message.success("删除成功");
      }
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      if (data.length > 0) {
        columns.forEach((column, index) => {
          if (index == 0) {
            sums[index] = "合计";
          }
          if (column.label == "应收金额" || column.label == "实收金额") {
            const values = data.map((item) => Number(item[column.property]));
            if (!values.every((value) => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              // sums[index] += "元";
            } else {
              sums[index] = "0";
              // sums[index] = "0元";
            }
          }
        });
      }
      return sums;
    },
    info(row, status) {
      this.init();
      this.readOnly = status;
      const id = row.fId ? row.fId : row;
      getdetail(id).then((res) => {
        if (res.data.tFee.fFromDate && res.data.tFee.fToDate) {
          const date = [];
          date.push(res.data.tFee.fFromDate, res.data.tFee.fToDate);
          res.data.tFee.date = date;
        }
        this.form = res.data.tFee;
        this.tableData = res.data.tFeeDo;
      });
    },
    copyData(id) {
      this.init();
      getdetail(id).then((res) => {
        if (res.data.tFee.fFromDate && res.data.tFee.fToDate) {
          const date = [];
          date.push(res.data.tFee.fFromDate, res.data.tFee.fToDate);
          res.data.tFee.date = date;
        }
        delete res.data.tFee.fId;
        delete res.data.tFee.fBillstatus;
        delete res.data.tFee.fBillno;
        delete res.data.tFee.srcBillNo;
        delete res.data.tFee.createBy;
        delete res.data.tFee.createTime;
        delete res.data.tFee.updateBy;
        delete res.data.tFee.updateTime;
        delete res.data.tFee.fRemarks;
        this.form = res.data.tFee;
      });
    },
    returnData() {
      this.addOrUpdateVisib = false;
      this.homepaGe();
    },
    homepaGe() {
      let view = {
        fullPath: "/finance/contrast",
        hash: "",
        matched: Array(2),
        meta: Object,
        name: "Contrast",
        params: Object,
        path: "/finance/contrast",
        query: Object,
        title: "对账",
      };
      this.$router.push({ path: "/index" });
      this.$store
        .dispatch("tagsView/delView", view)
        .then(({ visitedViews }) => {
          if (this.isActive(view)) {
            this.toLastView(visitedViews, view);
          }
        });
      Global.$emit("removeCache", "closeSelectedTag", view);
    },
    // 审批按钮
    goApproval(status) {
      this.addOrUpdateVisib = true;
      this.$nextTick(() => {
        this.$refs.ApprovalComments.init(this.form.fId, status, 430);
      });
    },
    // 撤销审批
    backApproval(status) {
      let data = {
        id: this.form.fId,
        actId: 430,
        billId: this.form.fId,
        fidStatus: status,
      };
      RevocationApproval(data).then((response) => {
        if (response.code === 200) {
          this.msgSuccess("撤销审批成功");
          this.open = false;
        }
      });
    },
    returnData() {
      this.$emit("goBack", false);
    },
    // 查看审批流
    addOrUpdateHandle(status) {
      this.addOrUpdateVisible = true;
      this.addOrUpdateVisib = false;
      let id = null;
      if (this.form.fId) {
        id = this.form.fId;
      } else {
        id = this.form.id;
      }
      this.$nextTick(() => {
        this.$refs.viewApproval.init(id, 430, status);
      });
    },
    // 撤销对账
    backrRconciliation() {
      this.form.fBillstatus = "1";
      let formDate = new window.FormData();
      formDate.append("tFee", JSON.stringify(this.form));
      formDate.append("tFeeDo", JSON.stringify(this.tableData));
      revoke(formDate).then((response) => {
        this.msgSuccess("撤回成功");
        this.$emit("goBack", false);
      });
    },
    Search() {
      const data = {
        fReconciliation: this.form.fReconciliation,
        fDc: this.form.fDc,
        fSystemType: 3,
        fCorpid: this.form.fCorpid,
        fVslid: this.form.fVslid,
        fVoyid: this.form.fVoyid,
        fDestportid: this.form.fDestportid,
        fLoadportid: this.form.fLoadportid,
        fMblno:this.form.tMblno,
        fFromDate: this.form.date ? this.form.date[0] : null,
        fToDate: this.form.date ? this.form.date[1] : null,
      };
      this.$refs.addOrUpdate.init(data, this.tableData);
    },
    imporData(rows) {
      this.tableData = this.tableData.concat(rows);
    },
    lumpSum() {
      let fAmtdr = 0;
      let fAmtcr = 0;
      this.tableData.map((e) => {
        fAmtdr = _.add(fAmtdr, Number(e.fAmtdr));
        fAmtcr = _.add(fAmtcr, Number(e.fAmt));
      });
      this.form.fAmtdr = fAmtdr;
      this.form.fAmtcr = fAmtcr;
    },
    submit() {
      if (this.form.fCorpid == null) {
        return this.$message.error("客户名称不能为空");
      }
      this.corpList.forEach((e) => {
        if (this.form.fCorpid == e.fId) {
          this.form.fCtrlcorpid = e.fName;
        }
      });
      if (this.tableData.length == 0) {
        return this.$message.error("明细表不能为空");
      }
      if (this.form.date) {
        this.form.fFromDate = this.form.date[0];
        this.form.fToDate = this.form.date[1];
      }
      this.lumpSum();
      if (this.form.fId == null) {
        return this.$message.error("数据未保存,不能进行确认对账");
      }
      let formDate = new window.FormData();
      formDate.append("tFee", JSON.stringify(this.form));
      formDate.append("tFeeDo", JSON.stringify(this.tableData));
      formDate.append("billsType", JSON.stringify("KHDZ"));
      confirm(formDate).then((res) => {
        if (res.code == 200) {
          this.$emit("goBack", false);
          this.$message.success("对账成功");
        }
      });
    },
    save(type) {
      if (this.form.fCorpid == null) {
        return this.$message.error("客户名称不能为空");
      }
      this.corpList.forEach((e) => {
        if (this.form.fCorpid == e.fId) {
          this.form.fCtrlcorpid = e.fName;
        }
      });
      if (this.form.date) {
        this.form.fFromDate = this.form.date[0];
        this.form.fToDate = this.form.date[1];
      }
      this.lumpSum();
      let formDate = new window.FormData();
      formDate.append("tFee", JSON.stringify(this.form));
      formDate.append("tFeeDo", JSON.stringify(this.tableData));
      formDate.append("billsType", JSON.stringify("KHDZ"));
      save(formDate).then((res) => {
        if (res.code == 200) {
          if (!type) {
            if (res.data.tFee.fFromDate && res.data.tFee.fToDate) {
              const date = [];
              date.push(res.data.tFee.fFromDate, res.data.tFee.fToDate);
              res.data.tFee.date = date;
            }
            this.form = res.data.tFee;
            this.tableData = res.data.tFeeDo;
          }
          this.$emit("refFresh");
          this.$message.success("保存成功");
        }
      });
    },
    cancel() {
      if (this.readOnly != 0) {
        this.$confirm("返回列表，是否保存?", "提示", {
          confirmButtonText: "保存",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.save("back");
            Object.assign(this.$data, this.$options.data());
            this.$emit("goBack", false);
          })
          .catch(() => {
            Object.assign(this.$data, this.$options.data());
            this.$emit("goDetail", false);
          });
      } else {
        Object.assign(this.$data, this.$options.data());
        this.$emit("goBack", false);
      }
    },
  },
  watch: {
    info: function (obj) {
      console.log(obj);
    },
  },
};
</script>
<style lang="scss" scoped>
.head-but {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}
.tabSetting {
  display: flex;
  justify-content: flex-end;
}
</style>
