<template>
  <div
    class="invoice-exception"
    v-loading="loading"
    element-loading-text="拼命加载中......请稍等"
  >
    <el-container>
      <el-form ref="form" style="width: 100%">
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item>
              <el-select
                v-model="search.invoiceType"
                placeholder="请选择发票类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in invoiceTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-select
                v-model="search.invoiceCategory"
                placeholder="请选择发票种类"
                style="width: 100%"
              >
                <el-option
                  v-for="item in invoiceCategoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-date-picker
                v-model="search.dateRange"
                type="daterange"
                unlink-panels
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                :clearable="false"
              >
                <template slot="prepend">开票日期</template>
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <div>
              <el-button
                @click="handleSearch"
                type="primary"
                icon="el-icon-search"
                >搜索
              </el-button>
              <el-button @click="handleResetSearch">重置 </el-button>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item>
              <el-input
                v-model.trim="search.belongEntName"
                clearable
                placeholder="请输入..."
              >
                <template slot="prepend">销方名称</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-input
                v-model.trim="search.customerName"
                clearable
                placeholder="请输入..."
              >
                <template slot="prepend">购方名称</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-input
                v-model.trim="search.invoicePerson"
                clearable
                placeholder="请输入..."
              >
                <template slot="prepend">开票人</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item>
              <el-input
                v-model.trim="search.timeOut"
                clearable
                placeholder="请输入..."
              >
                <template slot="prepend">开票超时时间(分钟) </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-container>
    <br />
    <el-container>
      <el-table
        :data="search.resultList"
        stripe
        border
        :height="tableHeight"
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        >
        <el-table-column
          type="index"
          :index="pageIndex"
          label="序号"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="invoiceReqFlowNo"
          label="请求流水号"
          width="120"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="invoiceType"
          label="发票类型"
          width="100"
          align="center"
          :formatter="fmtInvoiceType"
        ></el-table-column>
        <el-table-column
          prop="invoiceCategory"
          label="发票种类"
          width="160"
          align="center"
          :formatter="fmtInvoiceCategory"
        ></el-table-column>
        <el-table-column
          prop="invoiceStatusMemo"
          label="发票状态"
          width="120"
        ></el-table-column>

        <el-table-column
          prop="errorMsg"
          label="错误信息"
          width="120"
          show-overflow-tooltip
        ></el-table-column>

        <el-table-column
          prop="createTime"
          label="开票日期"
          width="160"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="belongEntName"
          label="销方名称"
          width="240"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="belongEntTaxId"
          label="销方纳税人识别号"
          width="180"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="customerName"
          label="购方名称"
          width="240"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="customerEntTaxId"
          label="购方纳税人识别号"
          width="180"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="totalAmount"
          label="合计金额"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="totalTaxes"
          label="合计税额"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="totalAmountTaxes"
          label="价税合计"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="invoicePerson"
          label="开票人"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="interactTypeDetail"
          label="电子邮件"
          width="180"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="invoiceCode"
          label="发票代码"
          width="120"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="invoiceNumber"
          label="发票号码"
          width="120"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="450" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              @click="handleInvoiceRefresh(scope.row)"
              :disabled="handleInvoiceRefreshDisabled(scope.row)"
              type="primary"
              >刷新
            </el-button>
            <el-button
              @click="handleInvoiceRetry(scope.row)"
              :disabled="handleInvoiceRetryDisabled(scope.row)"
              type="primary"
              >重试
            </el-button>
            <el-button @click="handleInvoiceSetFailed(scope.row)" type="primary"
              >置为失败
            </el-button>
            <el-button @click="handleInvoiceReqParams(scope.row)" type="primary"
              >开票请求参数
            </el-button>
            <el-button @click="invoiceRepair(scope.row)" type="primary"
              >发票修复
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-container>

    <br />
    <el-row type="flex" :gutter="20">
      <el-col :span="12"></el-col>
      <el-col :span="12">
        <div style="text-align: right">
          <el-pagination
            layout="total, sizes, prev, pager, next"
            :current-page="search.resultPagination.currentPage"
            :page-sizes="search.resultPagination.pageSizes"
            :page-size="search.resultPagination.pageSize"
            :total="search.resultPagination.total"
            @size-change="handleSearchResultSizeChange"
            @current-change="handleSearchResultCurrentChange"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>

    <el-dialog
      title="开票请求参数"
      :visible.sync="cmdParamInfo.dialogVisible"
      width="1200px"
      center
      append-to-body
      @close="handleCmdParamDialogClose"
    >
      <div v-if="cmdParamInfo.displayText">
        <el-alert
          v-if="cmdParamInfo.row.errorMsg"
          :title="'发票错误消息：' + cmdParamInfo.row.errorMsg"
          type="error"
          :closable="false"
          class="error-msg-alert"
        >
        </el-alert>
        <div class="cmd-param-wrap">
          <el-container class="item">
            <el-header style="white-space:nowrap;">原始请求参数</el-header>
            <el-main>
              <JSONEditor v-model="cmdParamInfo.displayTextCopy" />
            </el-main>
          </el-container>
          <el-container class="item">
            <el-header>
              <span style="white-space:nowrap;">当前编辑请求参数</span>
              <span style="text-align: right;width: 100%;">
                <el-select
                  v-model="cmdParamInfo.replaceValue"
                  placeholder="请选择"
                  :loading="cmdParamInfo.loadingReplaceOptions"
                  @visible-change="handleLoadingCmdParamReplaceOptions"
                >
                  <el-option
                    v-for="(item, index) in cmdParamInfo.replaceOptions"
                    :key="index"
                    :label="item.changeDesc"
                    :value="index"
                  >
                  </el-option>
                </el-select>
                <el-button @click="handleCmdParamReplace">
                  字符替换
                </el-button>
                <el-button
                  type="primary"
                  :loading="cmdParamInfo.loadingUpd"
                  @click="handleInvoiceUpdReqParams"
                >
                  提交修改
                </el-button>
              </span>
            </el-header>
            <el-main>
              <JSONEditor
                v-model="cmdParamInfo.displayText"
                ref="editJSONEditor"
              />
            </el-main>
          </el-container>
        </div>
      </div>

      <el-container v-else>
        <div style="width: 100%; text-align: center">
          暂无数据
        </div>
      </el-container>
    </el-dialog>
  </div>
</template>

<script>
import {
  invoiceAbnormalQuery,
  invoiceRefresh,
  invoiceRetry,
  invoiceSetFailed,
  invoiceGetReqParams,
  invoiceUpdReqParams,
  getSpeChars,
} from "@/api/invoice";

import DateHelper from "@/utils/date";
import SKServer from "../../api/skserver";
import JSONEditor from "@/components/JSONEditor";

// 发票种类列表
const invoiceCategoryOptions = [
  {
    value: 1,
    label: "增值税普通电子发票",
  },
  {
    value: 2,
    label: "增值税电子专用发票",
  },
  {
    value: 3,
    label: "增值税普通纸质发票",
  },
  {
    value: 4,
    label: "增值税专用纸质发票",
  },
];

const invoiceTypeOptions = [
  {
    value: 0,
    label: "蓝字发票",
  },
  {
    value: 1,
    label: "红字发票",
  },
  {
    value: 2,
    label: "空白作废发票",
  },
];

/**
 * 获取发票种类文本；
 * @param {Number} intKey 发票类别的数字标识
 */
function GetInvoiceCategoryLabel(intKey) {
  let result = intKey;
  for (const item of invoiceCategoryOptions) {
    if (item.value === intKey) {
      result = item.label;
      break;
    }
  }
  return result;
}

export default {
  name: "invoice_exception",

  components: { JSONEditor },

  data: function() {
    return {
      loading: false,
      invoiceCategoryOptions: invoiceCategoryOptions,
      invoiceTypeOptions: invoiceTypeOptions,
      search: {
        timeOut: 0,
        invoiceType: "",
        invoicePerson: "",
        invoiceCategory: "",
        belongEntTaxId: "",
        belongEntName: "",
        customerEntTaxId: "",
        customerName: "",
        dateRange: [
          DateHelper.LocalCurrentMonthStart(),
          DateHelper.LocalCurrentMonthEnd(),
        ],
        resultList: [],
        resultPagination: {
          currentPage: 1,
          pageSizes: [10, 30, 50, 100],
          pageSize: 10,
          total: 0,
        },
      },
      cmdParamInfo: {
        row: null,
        dialogVisible: false,
        displayText: "",
        displayTextCopy: "", // 原始内容拷贝；
        loadingUpd: false,

        loadingReplaceOptions: false,
        replaceOptions: [],
        replaceValue: null,
        speCharList: [],
      },
      tableHeight: "",
    };
  },
  created: function() {
    this.tableHeight = window.innerHeight - 250;
    this.callInvoiceAbnormalQuery(
      this.search.resultPagination.currentPage,
      this.search.resultPagination.pageSize
    );
  },

  mounted() {
    this.tableHeight = window.innerHeight - 250;
    window.onresize = () => {
      return (() => {
        this.tableHeight = window.innerHeight - 250;
      })();
    };
  },
  methods: {
    tableRowClassName({ row }) {
      if (row.errorMsg) {
        console.log("row", row);
        return "error-row";
      }
      return "";
    },

    pageIndex(index) {
      let currentPage = this.search.resultPagination.currentPage; // 当前页码，具体看组件取值
      let pageSize = this.search.resultPagination.pageSize; // 每页条数，具体是组件取值
      return index + 1 + (currentPage - 1) * pageSize;
    },
    fmtInvoiceType(row, column, cellValue) {
      let result = cellValue;
      for (const item of invoiceTypeOptions) {
        if (item.value === cellValue) {
          result = item.label;
          break;
        }
      }
      return result;
    },
    fmtInvoiceCategory(row, column, cellValue) {
      return GetInvoiceCategoryLabel(cellValue);
    },
    handleSearch() {
      this.callInvoiceAbnormalQuery(1, this.search.resultPagination.pageSize);
    },
    handleResetSearch() {
      this.search.timeOut = 0;
      this.search.invoiceType = "";
      this.search.invoicePerson = "";
      this.search.invoiceCategory = "";
      this.search.belongEntTaxId = "";
      this.search.belongEntName = "";
      this.search.customerEntTaxId = "";
      this.search.customerName = "";
      this.search.dateRange = [
        DateHelper.LocalCurrentMonthStart(),
        DateHelper.LocalCurrentMonthEnd(),
      ];
    },
    handleSearchResultSizeChange(val) {
      this.callInvoiceAbnormalQuery(1, val);
    },
    handleSearchResultCurrentChange(val) {
      this.callInvoiceAbnormalQuery(val, this.search.resultPagination.pageSize);
    },
    // 发票刷新按钮是否禁用；
    handleInvoiceRefreshDisabled(row) {
      return row.status != 1;
    },
    // 发票刷新；
    handleInvoiceRefresh(row) {
      this.loading = true;
      let _this = this;
      // invoiceType: 0:蓝票 1:红票
      // let funcRefresh =
      //     row.invoiceType === 0
      //         ? invoiceRefresh
      //         : hongchongInvoiceRefresh;
      invoiceRefresh(row.invoiceReqFlowNo)
        .then((val) => {
          _this.$message.success(val.msg);
          _this.loading = false;
          return _this.callInvoiceAbnormalQuery(
            _this.search.resultPagination.currentPage,
            _this.search.resultPagination.pageSize
          );
        })
        .catch((err) => {
          _this.$message.error(err);
          _this.loading = false;
        });
    },
    // 发票重试按钮是否禁用；
    handleInvoiceRetryDisabled(row) {
      // return row.status != 2;
      return false;
    },
    // 发票重试；
    handleInvoiceRetry(row) {
      this.loading = true;
      let _this = this;
      // invoiceType: 0:蓝票 1:红票
      // let funcRefresh =
      //     row.invoiceType === 0 ? invoiceRetry : hongchongInvoiceRetry;
      invoiceRetry(row.invoiceReqFlowNo, row.status)
        .then((val) => {
          _this.$message.success(val.msg);
          _this.loading = false;
          return _this.callInvoiceAbnormalQuery(
            _this.search.resultPagination.currentPage,
            _this.search.resultPagination.pageSize
          );
        })
        .catch((err) => {
          _this.$message.error(err);
          _this.loading = false;
        });
    },
    // 置为失败
    handleInvoiceSetFailed(row) {
      let _this = this;
      _this
        .$prompt(
          "请确认百望云开票队列中无该请求流水号对应的开票数据，否则易造成发票数据丢失。",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            inputPlaceholder: "请输入置为失败的原因",
          }
        )
        .then(({ value }) => {
          _this.loading = true;
          invoiceSetFailed(row.invoiceReqFlowNo, row.belongEntTaxId, value)
            .then((val) => {
              _this.$message.success(val.msg);
              _this.loading = false;
              return _this.callInvoiceAbnormalQuery(
                _this.search.resultPagination.currentPage,
                _this.search.resultPagination.pageSize
              );
            })
            .catch((err) => {
              _this.$message.error(err);
              _this.loading = false;
            });
        })
        .catch(() => {
          // 取消操作
        });
    },
    /**
     * 查询发票
     * @param {Number} pageNum : 当前页码
     * @param {Number} pageSize : 每页数量
     */
    callInvoiceAbnormalQuery(pageNum, pageSize) {
      if (this.search.timeOut != "") {
        if (!Number.isInteger(this.search.timeOut)) {
          this.$message.error("开票超时时间(分钟)必须是整数！");
          return false;
        }
      }

      let beginTime = "";
      let endTime = "";
      if (this.search.dateRange instanceof Array) {
        beginTime = this.search.dateRange[0];
        endTime = this.search.dateRange[1];
        beginTime = this.dateFormat(new Date(beginTime), "yyyy-MM-dd HH:mm:ss");
        let endTimeObj = new Date(endTime);
        endTime = this.dateFormat(
          new Date(
            endTimeObj.getFullYear(),
            endTimeObj.getMonth(),
            endTimeObj.getDate(),
            "23",
            "59",
            "59"
          ),
          "yyyy-MM-dd HH:mm:ss"
        );
      } else {
        this.$message.error("起始日期与结束日期为必输项，请确定后重试！");
        return false;
      }

      this.loading = true;
      let _this = this;
      invoiceAbnormalQuery({
        timeOut: this.search.timeOut,
        invoiceType: this.search.invoiceType,
        invoicePerson: this.search.invoicePerson,
        invoiceCategory: this.search.invoiceCategory,
        belongEntTaxId: this.search.belongEntTaxId,
        belongEntName: this.search.belongEntName,
        customerEntTaxId: this.search.customerEntTaxId,
        customerName: this.search.customerName,
        invoiceDateBegin: beginTime,
        invoiceDateEnd: endTime,
        pageNum: pageNum,
        pageSize: pageSize,
      })
        .then((val) => {
          _this.search.resultPagination.total = val.data.total;
          _this.search.resultPagination.pageSize = val.data.size;
          _this.search.resultPagination.currentPage = val.data.current;
          _this.search.resultList = val.data.records;
          _this.loading = false;
        })
        .catch((err) => {
          _this.$message.error(err);
          _this.loading = false;
        });
    },
    handleInvoiceReqParams(row) {
      let _this = this;
      _this.cmdParamInfo.displayText = "";
      _this.cmdParamInfo.displayTextCopy = "";
      _this.loading = true;
      invoiceGetReqParams(row.cmdId)
        .then((val) => {
          _this.loading = false;
          _this.cmdParamInfo.row = row;
          _this.cmdParamInfo.displayText = val.data.cmdParam;
          _this.cmdParamInfo.displayTextCopy = val.data.cmdParam;
          _this.cmdParamInfo.dialogVisible = true;
        })
        .catch((err) => {
          _this.loading = false;
          _this.$message.error(err);
        });
    },
    dateFormat(date, fmt) {
      // 小时只支持24小时制
      var o = {
        "M+": date.getMonth() + 1, // 月份
        "d+": date.getDate(), // 日
        "H+": date.getHours(), // 24小时,
        "m+": date.getMinutes(), // 分
        "s+": date.getSeconds(), // 秒
        "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      }
      return fmt;
    },
    async invoiceRepair(row) {
      let device = "";
      let time = "";
      let beginTime = "";
      let endTime = "";
      if (row.invoiceChannel.length > 0) {
        device = row.invoiceChannel.split("-")[1];
      }
      if (row.createTime.length > 0) {
        time = row.createTime.split(" ")[0];
        beginTime = time + " 00:00:00";
        endTime = time + " 23:59:59";
      }
      let res = await SKServer.deviceInvoiceRecovery({
        tax_no: row.belongEntTaxId,
        device_no: device,
        start_date: beginTime,
        end_date: endTime,
      });
      if (res) {
        // eslint-disable-next-line no-debugger
        debugger;
        if (res.code === 0) {
          this.$message({
            message: "发票修复成功，" + res.message,
            type: "success",
          });
        } else {
          this.$message.error(res.msg);
        }
      } else {
        this.$message.error(res.msg);
      }
    },

    handleInvoiceUpdReqParams() {
      let jsonObject = this.cmdParamInfo.displayText;
      if (typeof jsonObject === "string") {
        try {
          jsonObject = JSON.parse(jsonObject);
        } catch (error) {
          this.$message.error("JSON 错误：" + error);
          return false;
        }
      }

      const _this = this;
      _this.cmdParamInfo.loadingUpd = true;
      invoiceUpdReqParams(
        _this.cmdParamInfo.row.cmdId,
        _this.cmdParamInfo.speCharList,
        jsonObject
      )
        .then((val) => {
          _this.$message.success(val.msg);
          _this.cmdParamInfo.dialogVisible = false;
          _this.callInvoiceAbnormalQuery(
            _this.search.resultPagination.currentPage,
            _this.search.resultPagination.pageSize
          );
        })
        .catch((err) => {
          _this.$message.error(err);
        })
        .finally(() => {
          _this.cmdParamInfo.loadingUpd = false;
        });
    },
    handleLoadingCmdParamReplaceOptions(visible) {
      if (visible) {
        if (
          !this.cmdParamInfo.replaceOptions ||
          (this.cmdParamInfo.replaceOptions &&
            this.cmdParamInfo.replaceOptions.length <= 0)
        ) {
          this.cmdParamInfo.loadingReplaceOptions = true;
          getSpeChars()
            .then((res) => {
              console.log("res", res);
              this.cmdParamInfo.replaceOptions = res.data;
            })
            .catch((error) => {
              this.$message.error(error);
            })
            .finally(() => {
              this.cmdParamInfo.loadingReplaceOptions = false;
            });
        }
      }
    },
    handleCmdParamReplace() {
      if (this.cmdParamInfo.replaceValue === null) {
        return false;
      }
      // eslint-disable-next-line standard/computed-property-even-spacing
      const info = this.cmdParamInfo.replaceOptions[
        this.cmdParamInfo.replaceValue
      ];
      const replaceResult = this.$refs.editJSONEditor.replace(
        info.speChar,
        info.replaceChar
      );
      if (replaceResult) {
        this.cmdParamInfo.speCharList.push(info.speChar);
        console.log("替换成功", this.cmdParamInfo.speCharList);
        this.$message.success("替换成功");
      } else {
        this.$message.warning("无可替换字符");
      }
    },

    handleCmdParamDialogClose() {
      this.cmdParamInfo.speCharList = [];
      this.cmdParamInfo.replaceValue = null;
    },
  },
};
</script>

<style lang="scss" scoped>
.invoice-exception {
  ::v-deep.el-table .error-row .el-table__cell {
    background: #f56c6c;
    color: white;
  }
}

.actions {
  flex: auto;
}

.error-msg-alert {
  margin-bottom: 20px;
}

.cmd-param-wrap {
  display: flex;

  .el-header {
    background-color: #e9eef3;
    display: flex;
    align-items: center;
    height: auto;
  }

  .el-main {
    background-color: #e9eef3;
    padding: 0;
  }

  .item {
    margin-right: 20px;

    &:last-child {
      margin-right: 0;
    }
  }
}
</style>
