<template>
  <basic-container>
    <div>
      <Card class="cardTitle">
        <p>
          <el-button type="primary" @click="backPage" style="width: 80px"
            >返回</el-button
          >
          <el-button type="primary" @click="importEvidenceOpen" class="ml15"
            >导入证据链</el-button
          >
        </p>
      </Card>

      <avue-crud
        style="width: 100%; margin-top: 15px"
        :data="tableData"
        :option="option"
        :page.sync="page"
        :table-loading="tableLoading"
        @on-load="getList"
        @size-change="sizeChange"
        @current-change="currentChange"
        @search-change="searchChange"
      >
        <template slot="menu" slot-scope="scope">
          <!--          <el-button-->
          <!--            type="text"-->
          <!--            size="small"-->
          <!--            icon="el-icon-view"-->
          <!--            :disabled="typeVal == 'lookType'"-->
          <!--            @click="settleById(scope.row.id)"-->
          <!--            >结算-->
          <!--          </el-button>-->

          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            :disabled="typeVal == 'jdspType'"
            v-show="typeVal == 'zjlscType'"
            @click="proofTopload(scope.row, scope.index)"
            >证据链上传
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            v-show="typeVal != 'jdspType'"
            @click="lookBtn(scope.row, scope.index)"
            >查看
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            v-show="typeVal == 'jdspType'"
            :disabled="scope.row.status != '1'"
            @click="examineBtn(scope.row, scope.index)"
            >审核
          </el-button>
        </template>
      </avue-crud>
    </div>

    <!--结算弹出框-->
    <el-dialog
      title="结算"
      :close-on-click-modal="false"
      @close="close"
      :visible.sync="settleTableVisible"
      center
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules1"
        label-width="120px"
        :inline="true"
      >
        <div class="separator">积分包基本信息</div>
        <el-form-item
          label="积分包名称"
          prop="scorePackageName"
          class="settle-label"
        >
          <el-input
            v-model="form.scorePackageName"
            :disabled="true"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="积分包值" prop="score" class="settle-label">
          <el-input
            v-model="form.score"
            :disabled="true"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <div class="separator">结算信息</div>
        <el-form-item
          label="发票类目"
          prop="invoiceCategory"
          class="settle-label"
        >
          <el-select
            v-model="form.invoiceCategory"
            placeholder="请选择发票类目"
          >
            <el-option
              v-for="item in invoiceVal"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table
        :data="gridData"
        :summary-method="getSummaries"
        border
        show-summary
        class="settle-grid"
      >
        <el-table-column
          type="index"
          width="60"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column
          property="realName"
          label="结算对象"
          align="center"
        ></el-table-column>
        <el-table-column property="discount" label="折扣" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.discount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          property="settleAmount"
          label="结算金额"
          align="center"
        >
          <template slot-scope="scope">
            <el-input
              v-if="settleButtonShow && scope.row.settleNoteStatus === 0"
              v-model="scope.row.settleAmount"
              placeholder="请输入结算金额"
              @change="settleAmountChange(scope.row)"
              @input="settleAmountInput(scope.row)"
            ></el-input>
            <span v-else>{{ scope.row.settleAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          property="settleNoteStatus"
          label="状态"
          align="center"
        >
          <template slot-scope="scope">
            <span
              v-if="scope.row.settleNoteStatus === 2"
              style="color: #f56c6c"
            >
              {{ scope.row.settleNoteStatus | filterNoteStatus }}</span
            >
            <span
              v-else-if="scope.row.settleNoteStatus === 1"
              style="color: #67c23a"
            >
              {{ scope.row.settleNoteStatus | filterNoteStatus }}</span
            >
            <span v-else>
              {{ scope.row.settleNoteStatus | filterNoteStatus }}</span
            >
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="hideDialog" icon="el-icon-close">取 消</el-button>
        <el-button
          v-show="settleButtonShow"
          type="primary"
          :loading="buttonLoading"
          icon="el-icon-check"
          @click="settleSave()"
          >保 存</el-button
        >
        <el-button
          v-show="settleButtonShow"
          type="primary"
          :loading="buttonLoading"
          icon="el-icon-check"
          @click="settleSubmit()"
          >提 交</el-button
        >
      </span>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog
      title="审核"
      :visible.sync="showDialog"
      width="50%"
      center
      :before-close="handleClose"
    >
      <el-form
        :model="taskForm"
        :rules="rules"
        ref="taskForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <p class="teskDetailsty">审批意见</p>

        <el-form-item label="审批意见:" prop="taskStatus">
          <el-radio-group v-model="taskForm.taskStatus">
            <el-radio label="2">通过</el-radio>
            <el-radio label="3">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="说明:">
          <el-input type="textarea" v-model="taskForm.approvalInfo"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelBtn">取 消</el-button>
        <el-button type="primary" @click="sureBtn('taskForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导入证据链 -->
    <el-dialog
      title="导入证据链"
      :visible.sync="importEvidenceShow"
      width="400px"
      :before-close="importEvidenceClose"
    >
      <div class="tc" v-loading="importLoading">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          :before-upload="handleBefore"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :limit="1"
          :on-exceed="handleExceed"
          :on-success="handleSuccess"
          :on-error="handleError"
          accept=".xls,.xlsx"
          :file-list="evidenceFileList"
          :show-file-list="false"
        >
          <el-button size="small" type="primary"
            >上传文件（Excel文件）</el-button
          >
        </el-upload>
        <br />
        <el-button type="text" @click="handleDown">下载模板</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="上传失败！"
      width="600px"
      :close-on-click-modal="false"
      @close="importErrorDialogClose"
      :visible.sync="importErrorDialogShow"
      center
    >
      <avue-crud
        style="width: 100%;"
        :data="importErrorTableData"
        :option="option1"
      >
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  receiptApprovalData,
  importErrorTableOption
} from "@/const/crud/assignPoints/settlement/manList";
import {
  getPage,
  settleById,
  settleSave,
  settleSubmit,
  approvalStatus,
  templateDownload,
  getPackageById
} from "@/api/assignPoints/currency/manList";
import store from "@/store";
import { upload } from "@/api/projectManagement";

export default {
  name: "receiptApproval",
  data() {
    return {
      tableData: [],
      option: receiptApprovalData,
      page: {
        pageSize: 10,
        pagerCount: 5
      },
      tableLoading: false,
      searchForm: {},
      typeVal: "",
      settleTableVisible: false,
      form: {},
      rules1: {
        invoiceCategory: [
          { required: true, message: "请选择发票类目", trigger: "blur" }
        ]
      },
      rules: {
        taskStatus: [
          { required: true, message: "请选择审批意见", trigger: "change" }
        ]
      },
      gridData: [],
      settleButtonShow: false,
      buttonLoading: false,
      invoiceVal: [
        {
          label: "现代服务*技术咨询服务费",
          value: 3
        },
        {
          label: "现代服务*推广服务费",
          value: 7
        },
        {
          label: "现代服务*其他咨询服务费",
          value: 4
        },
        {
          label: "现代服务*现场辅助服务费",
          value: 5
        }
      ],
      showDialog: false,
      taskForm: {},
      examineVal: "",
      importEvidenceShow: false,
      evidenceFileList: [],
      headers: {
        Authorization: "Bearer " + store.getters.access_token
      },
      importLoading: false,
      importErrorDialogShow: false,
      option1: importErrorTableOption,
      importErrorTableData: [],
      uploadUrl: "/admin/wmtask/task-batch-import",
      packageName: ""
    };
  },
  created() {
    this.typeVal = this.$route.query.type;
    this.getPackageById();
  },
  methods: {
    // 根据积分包id获取积分包名称
    getPackageById() {
      let id = this.$route.query.id
        ? this.$route.query.id
        : this.$route.query.packageId;
      getPackageById({ id }).then(res => {
        this.packageName = res.data.data ? res.data.data.scorePackageName : "";
      });
    },
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    // 初始化页面
    getList(page, params) {
      this.tableLoading = true;
      if (this.typeVal != "jdspType") {
        this.searchForm.status = "2";
      } else {
        this.searchForm = {};
      }
      getPage(
        Object.assign(
          {
            packageId:
              this.$route.query.id == undefined
                ? this.$route.query.packageId
                : this.$route.query.id,
            // status: '2',
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.tableData = [];
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    // 返回按钮
    backPage() {
      this.$router.$avueRouter.closeTag();
      this.$router.push({ path: "/admin/assignPoints/settlement/index" });
    },

    // 查看按钮
    lookBtn(row) {
      this.$router.push({
        path:
          "/admin/assignPoints/settlement/taskList?id=" +
          row.id +
          "&type=manLookType" +
          "&taskUserId=" +
          row.taskUserId +
          "&packageId=" +
          this.$route.query.id
      });
    },

    // 证据链上传
    proofTopload(row) {
      this.$router.push({
        path:
          "/admin/assignPoints/settlement/taskList?id=" +
          row.id +
          "&type=zjlscType" +
          "&packageId=" +
          this.$route.query.id +
          "&taskUserId=" +
          row.taskUserId
      });
    },

    // 审核按钮
    examineBtn(row) {
      this.showDialog = true;
      this.examineVal = row.id;
    },
    // 审核-弹窗确定按钮
    sureBtn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let args = {
            id: this.examineVal,
            status: this.taskForm.taskStatus,
            packageId: this.$route.query.id
          };
          approvalStatus(args)
            .then(response => {
              this.showDialog = false;
              this.getList(this.page);
              this.tableLoading = false;
              this.taskForm = {};
              this.$message.success("审核成功");
            })
            .catch(() => {
              this.$message.error("审核失败");
              this.tableLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    settleAmountInput(e) {
      let value = e.settleAmount;
      value = value.replace(/[^\d.\-]/g, ""); //清除"数字"和"." "-"负号以外的字符
      value = value.replace(/\.{2,}/g, ""); //只保留第一个, 清除多余的
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数

      e.settleAmount = value;
    },

    settleAmountChange(e) {
      let value = e.settleAmount.toString();
      if (value) {
        value = value.replace(/[^\d.\-]/g, ""); //清除"数字"和"." "-"负号以外的字符
        value = value.replace(/\.{2,}/g, ""); //只保留第一个, 清除多余的
        value = value
          .replace(".", "$#$")
          .replace(/\./g, "")
          .replace("$#$", ".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数

        e.settleAmount = value;
      } else {
      }
    },

    //以下是结算的方法
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总价";
          return;
        }
        if (index === 3) {
          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] = "N/A";
          }
        } else {
          sums[index] = "*";
        }
      });

      return sums;
    },
    settleById(id) {
      this.settleButtonShow = true;
      const args = { id: id };
      settleById(args)
        .then(response => {
          const res = response.data.data;
          console.log(res);
          this.gridData = res.notes;
          this.form = res.wsp;
          this.id = res.wsp.id;
          this.scorePackageName = res.wsp.scorePackageName;
          this.score = res.wsp.score;
          this.settleTableVisible = true;
        })
        .catch(() => {
          // this.hideDialog();
        });
    },
    settleSave() {
      if (!this.id) {
        this.$message.error("数据异常");
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          for (var i = 0; i < this.gridData.length; i++) {
            const item = this.gridData[i];
            if (
              Number(item.discount) < Number(0.5) ||
              Number(item.discount) > Number(2)
            ) {
              this.$message.error(
                "第" + parseInt(i + 1) + "行，折扣应介于0.5~2之间"
              );
              return false;
            }
          }
          this.buttonLoading = true;
          const args = {
            id: this.id,
            invoiceCategory: this.form.invoiceCategory,
            notes: this.gridData
          };
          settleSave(args)
            .then(response => {
              if (response.data.code === 0) {
                this.$message.success("保存成功");
              }
              this.hideDialog();
              this.buttonLoading = false;
            })
            .catch(() => {
              this.buttonLoading = false;
              // this.hideDialog();
            });
        }
      });
    },
    settleSubmit() {
      if (!this.id) {
        this.$message.error("数据异常");
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          for (var i = 0; i < this.gridData.length; i++) {
            const item = this.gridData[i];
            if (
              Number(item.discount) < Number(0.5) ||
              Number(item.discount) > Number(2)
            ) {
              this.$message.error(
                "第" + parseInt(i + 1) + "行，折扣应介于0.5~2之间"
              );
              return false;
            }
          }
          this.buttonLoading = true;
          const args = {
            id: this.id,
            invoiceCategory: this.form.invoiceCategory,
            notes: this.gridData
          };
          settleSubmit(args)
            .then(response => {
              if (response.data.code === 0) {
                this.$message.success("提交成功");
              }
              this.hideDialog();
              this.buttonLoading = false;
            })
            .catch(() => {
              this.buttonLoading = false;
              // this.hideDialog();
            });
        }
      });
    },
    hideDialog() {
      this.settleTableVisible = false;
      this.form = {};
      this.gridData = [];
      this.getList(this.page, this.searchForm);
    },
    close() {
      this.settleTableVisible = false;
      this.$refs.form.resetFields();
    },
    // 取消按钮
    cancelBtn() {
      this.enableForm = {};
      this.taskForm = {};
      this.showDialog = false;
    },
    handleClose() {
      this.showDialog = false;
    },
    // 分页查询
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    // 导入证据链
    importEvidenceOpen() {
      if (!this.packageName) return this.$message.warning("未获取到积分包名称");
      this.uploadUrl =
        "/admin/wmtask/task-batch-import?packageName=" + this.packageName;
      this.importEvidenceShow = true;
    },
    importEvidenceClose() {
      this.importEvidenceShow = false;
      this.evidenceFileList = [];
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning("最多上传一个文件");
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(res, file) {
      this.importLoading = false;
      if (res.code === 1) {
        this.evidenceFileList = [];
        if (res.data && res.data.code === "FAILURE") {
          // 上传有错误
          this.importErrorTableData = [];
          const errorData = res.data.data;
          if (Object.keys(errorData).length > 0) {
            Object.keys(errorData).forEach(ele => {
              this.importErrorTableData.push({
                reason: ele,
                index: errorData[ele]
              });
            });
          }
          console.log(this.importErrorTableData);
          this.importErrorDialogShow = true;
        } else {
          // 上传失败
          this.$message.error(res.msg);
        }
      } else {
        this.$message.success("上传成功！");
        this.importEvidenceClose();
        this.getList(this.page);
      }
    },
    handleError() {
      this.importLoading = false;
    },
    async handleBefore(file) {
      this.importLoading = true;
      // 上传文件, 获取fileId
      var formData = new FormData();
      formData.append("file", file);
      const res = await upload(formData);
      if (res.data.code === 0) {
        let fileId = res.data.data.fileId;
        this.uploadUrl = this.uploadUrl + `&fileId=${fileId}`;
      } else {
        this.$message.error(res.data.msg);
        return false;
      }
    },
    handleDown() {
      this.importLoading = true;
      templateDownload({
        fileName: "CRO_evidence_dynamic_upload_template.xlsx"
      })
        .then(response => {
          this.importLoading = false;
          let url = window.URL.createObjectURL(new Blob([response.data]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute(
            "download",
            "CRO_evidence_dynamic_upload_template.xlsx"
          );
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(() => {
          this.importLoading = false;
        });
    },
    importErrorDialogClose() {
      this.importErrorDialogShow = false;
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.settle-label {
  width: 48%;

  ::v-deep .el-input__inner {
    width: 233px;
  }
}

.separator {
  background-color: rgba(242, 242, 242, 1) !important;
  text-align: center;
  width: 96%;
  height: 34px;
  line-height: 34px;
  margin-bottom: 2px;
}

.settle-grid {
  ::v-deep .el-input__inner {
    text-align: center;
    border: none;
  }
}

.treeBox {
  float: left;
  width: 25%;
}

/*滚动条样式*/
.treeBox::-webkit-scrollbar {
  width: 10px;
}

.treeBox::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background-color: #f90;
}

.treeBox::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.1);
}

.teskDetailsty {
  width: 100%;
  height: 30px;
  line-height: 30px;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  border-bottom: 1px solid #d7d6d5;
  margin: 0 0 15px 0;
}

.missionContsty {
  height: 300px;
  border: 1px solid #f2f2f2;
  margin-bottom: 15px;
}
</style>
