<template>
  <basic-container>
    <div>
      <avue-crud
        :data="tableData"
        :option="option"
        :page.sync="page"
        :table-loading="tableLoading"
        @on-load="getList"
        @size-change="sizeChange"
        @search-change="searchVal"
        @current-change="currentChange"
      >
        <template slot="menuLeft">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click.stop="addData()"
            >新增</el-button
          >
        </template>

        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-finished"
            @click="proofTopload(scope.row, scope.index)"
            v-show="scope.row.settleFlag != '1'"
            >证据链上传
          </el-button>

          <el-button
            type="text"
            size="small"
            icon="el-icon-tickets"
            v-show="scope.row.yjddsh != null && scope.row.yjddsh > 0"
            @click="receiveApproval(scope.row, scope.index)"
            >接单审批
          </el-button>

          <el-button
            type="text"
            size="small"
            icon="el-icon-tickets"
            v-show="scope.row.userListNum == 0"
            @click="updateSettle(scope.row, scope.index)"
            >编辑
          </el-button>

          <!--          <el-button-->
          <!--            type="text"-->
          <!--            size="small"-->
          <!--            icon="el-icon-close"-->
          <!--            @click="delBtn(scope.row, scope.index)"-->
          <!--            v-show="scope.row.settleStatus == null"-->
          <!--            >删除-->
          <!--          </el-button>-->

          <!--          <el-button-->
          <!--            v-if="scope.row.settleFlag == '0' && scope.row.shtg !=null"-->
          <!--            type="text"-->
          <!--            size="small"-->
          <!--            icon="el-icon-finished"-->
          <!--            @click="settleById(scope.row.id)"-->
          <!--            >结算-->
          <!--          </el-button>-->

          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="toView(scope.row, scope.index)"
            >查看
          </el-button>

          <el-button
            type="text"
            size="small"
            icon="el-icon-folder-checked"
            @click="exportBtn(scope.row, scope.index)"
            >导出
          </el-button>
        </template>
      </avue-crud>

      <!-- 导出弹窗 -->
      <el-dialog title="导出" :visible.sync="exportDig" width="30%" center>
        <span>
          <el-button
            @click="taskExport"
            :loading="taskExportLoading"
            style="margin-left: 40%;"
            >导出报告</el-button
          >

          <!--          <el-button-->
          <!--            @click="taskExportInfo"-->
          <!--            :loading="taskExportInfoLoading"-->
          <!--            style="margin-left: 50px"-->
          <!--          >导出报告详情</el-button-->
          <!--          >-->
        </span>
        <span slot="footer" class="dialog-footer">
          注意： 1.报告汇总为封面+任务数据汇总+任务列表明细。<br />

          2.报告详情为每条任务的任务详情+图片。
        </span>
      </el-dialog>

      <!-- 添加的弹窗 -->
      <el-dialog
        :title="showTit"
        :visible.sync="addDialog"
        width="60%"
        :before-close="handleClose"
        center
      >
        <el-form
          :model="addForm"
          :rules="rules"
          ref="addForm"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="积分包名称" prop="scorePackageName">
                <el-input v-model="addForm.scorePackageName"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="个人预计包值" prop="userScore">
                <el-input
                  v-model="addForm.userScore"
                  onkeyup="value=value.replace(/[^\d]/g,'')"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="接单对象类型" prop="typeid">
                <el-select
                  style="width: 100%"
                  v-model="addForm.typeid"
                  placeholder="请选择"
                  @change="typeidChange"
                >
                  <el-option
                    v-for="item in typeidList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- <el-col :span="12" v-show="showPackage">
              <el-form-item label="接单对象">
                <el-select
                  multiple
                  style="width: 100%"
                  v-model="addForm.userList"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in receivingObject"
                    :key="item.id"
                    :label="item.realname"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="需求人数" prop="userNum">
                <el-input
                  v-model="addForm.userNum"
                  onkeyup="value=value.replace(/[^\d]/g,'')"
                  @input="getUsernumval(addForm.userNum)"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="任务个数" prop="taskNum">
                <el-input
                  v-model="addForm.taskNum"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="任务类型" prop="taskTypeId">
                <el-select
                  v-model="addForm.taskTypeId"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in taskTypeList1"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="接单对象范围">
                <el-input
                  value="仅内部可见"
                  :disabled="userScopeAble"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-show="subTypeShow">
              <el-form-item label="结算渠道" prop="subjectLocation">
                <el-select
                  v-model="addForm.subjectLocation"
                  style="width: 100%"
                  @change="addSubTypeChange"
                >
                  <el-option
                    v-for="(item, index) in subList"
                    :value="item.subjectLocation"
                    :key="index"
                    :label="item.subjectLocation | filterSujectLocation"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectName">
                <el-select v-model="addForm.projectNum" style="width: 100%">
                  <el-option
                    v-for="(item, index) in allProjectList"
                    :value="item.projectNumber"
                    :key="index"
                    :label="item.projectName"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目编号" prop="projectNumber">
                <el-input :value="addForm.projectNum" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="积分包编号编号">
                <el-input :value="addForm.packageSn" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="描述">
                <el-input
                  type="textarea"
                  v-model="addForm.description"
                  placeholder="请描述推广的产品品种"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelBtn">取 消</el-button>
          <el-button
            type="primary"
            :loading="buttonLoading"
            @click="sureBtn('addForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!--      结算弹出框-->
      <el-dialog
        title="结算"
        :close-on-click-modal="false"
        @close="close"
        :visible.sync="settleTableVisible"
        center
      >
        <el-form
          ref="form"
          :model="form"
          :rules="settleRules"
          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 invoiceList"
                :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">
              <!--              <el-input v-if="settleButtonShow && scope.row.settleNoteStatus === 0" v-model="scope.row.discount" placeholder="请输入折扣"-->
              <!--                        @change="discountChange(scope.row)" @input="discountInput(scope.row)"></el-input>-->
              <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>
    </div>
  </basic-container>
</template>

<script>
import { settlementData } from "@/const/crud/assignPoints/settlement/index";
import { getPackageSn } from "@/api/assignPoints/quota";
import {
  getScorePackagePage,
  getRelationScoreList,
  typeid,
  objectScope,
  showDescription,
  addWmScorePackage,
  packageUserScope,
  exportZbInfoJs,
  updateEnable,
  updateWmScorePackage,
  getScorePackagePageById,
  getAllParentDept,
  getTaskTypeTree,
  searchById,
  saveById
} from "@/api/assignPoints/currency/index";

import {
  settleById,
  settleSave,
  settleIssue,
  settleReIssue,
  settleSubmit
} from "@/api/settle/settle";
import { getSubSelect } from "@/api/admin/deptSub";
import { getAllProject } from "@/api/archivesManagement/project";

export default {
  name: "allotPoints",
  data() {
    return {
      subList: [],
      packageSn: "",
      subTypeShow: true,
      addForm: {
        subjectLocation: "",
        packageUserScope: "1",
        packageSn: ""
      },
      typeidList: [
        {
          value: "4",
          label: "兼职CRC"
        }
      ],
      receivingObject: [],
      objectScopelist: [],
      userScopeAble: true,
      taskTypeList1: [],

      tableLoading: false,
      option: settlementData,
      tableData: [],
      page: {
        pageSize: 10,
        pagerCount: 5
      },
      exportDig: false,
      checkRow: null,
      taskExportLoading: false,
      taskExportInfoLoading: false,
      addDialog: false,
      rules: {
        scorePackageName: [
          { required: true, message: "请输入积分包名称", trigger: "blur" }
        ],
        userScore: [
          { required: true, message: "请输入个人预计包值", trigger: "blur" }
        ],
        typeid: [
          { required: true, message: "请选择接单对象类型", trigger: "change" }
        ],
        taskNum: [
          { required: true, message: "请输入任务个数", trigger: "blur" }
        ],
        taskTypeId: [
          { required: true, message: "请选择任务类型", trigger: "blur" }
        ],
        subjectLocation: [
          { required: true, message: "请选择结算渠道", trigger: "blur" }
        ],
        projectNum: [
          { required: true, message: "请选择项目名称", trigger: "change" }
        ],
        userNum: [
          { required: true, message: "请输入需求人数", trigger: "blur" }
        ]
      },
      showTit: "",
      settleTableVisible: false,
      buttonLoading: false,
      form: {},
      gridData: [],
      settleButtonShow: false,
      settleRules: {
        invoiceCategory: [
          { required: true, message: "请选择发票类目", trigger: "blur" }
        ],
        subjectLocation: [
          { required: true, message: "请选择结算渠道", trigger: "blur" }
        ]
      },
      invoiceList: [],
      invoiceList0: [
        { value: 3, label: "现代服务*技术咨询服务费" },
        { value: 7, label: "现代服务*推广服务费" },
        { value: 4, label: "现代服务*其他咨询服务费" },
        { value: 5, label: "现代服务*现场辅助服务费" }
      ],
      invoiceList1: [
        { value: 1, label: "推广服务费" },
        { value: 2, label: "营销服务费" },
        { value: 3, label: "信息服务费" }
      ],
      allProjectList: []
    };
  },
  mounted() {
    // this.typeidShow(); // 接单对象类型-展示
    this.showObjectscope(); // 接单对象-展示
    // this.showUserScope(); // 接单对象范围-展示
    this.getTaskTypeList(); // 任务类型列表
    this.showSubSelect();
    this.addForm.typeid = "4";
    this.getAllProject();
  },
  methods: {
    addSubTypeChange(val) {
      this.$message.closeAll();
      if (val === "REN_LI_JIA") {
        this.$message({
          message:
            "人力家单笔结算额不得超过5万元，请注意发包积分值，避免浪费积分",
          type: "warning"
        });
      }
    },
    // 查询项目管理列表(即查询所有)
    getAllProject() {
      getAllProject().then(res => {
        this.allProjectList = res.data.data;
      });
    },
    subTypeChange(e) {
      delete this.form.invoiceCategory;
      if (e == "0") {
        this.invoiceList = this.invoiceList0;
      } else {
        this.invoiceList = this.invoiceList1;
      }
    },
    showSubSelect() {
      getSubSelect()
        .then(response => {
          this.subList = response.data.data;
          if (!this.subList) {
            this.$message.error("当前机构未配置结算渠道");
            return;
          }
          let sub = this.subList.find(item => {
            return item.subjectLocation === "REN_LI_JIA";
          });
          if (sub) {
            this.addForm.subjectLocation = "REN_LI_JIA";
          } else {
            this.addForm.subjectLocation = this.subList[0].subjectLocation;
          }
          if (this.addForm.subjectLocation === "REN_LI_JIA") {
            this.invoiceList = this.invoiceList0;
          } else {
            this.invoiceList = this.invoiceList1;
          }
        })
        .catch(() => {
          this.$message.error("当前机构未配置结算渠道");
        });
    },
    typeidChange(id) {
      this.jddxVal = id;
      this.addForm.REN_LI_JIA = "";
      if (id == "3") {
        this.addForm.REN_LI_JIA = "";
        this.showPackage = true;
        this.addForm.packageUserScope = "1";
        this.userScopeAble = true;
        this.$message.warning("请选择接单对象");
      } else {
        // this.pointsForm.packageUserScope = ''
        this.showSubSelect();
        this.userScopeAble = false;
        this.showPackage = false;
      }
    },
    // 接单对象类型-展示
    // typeidShow() {
    //     typeid().then((response) => {
    //       this.typeidList = response.data.data;
    //     });
    // },

    // 接单对象展示
    showObjectscope() {
      objectScope().then(response => {
        this.receivingObject = response.data.data;
      });
    },

    // 接单对象范围-默认展示
    // showUserScope() {
    //     packageUserScope().then((response) => {
    //         this.objectScopelist = response.data.data

    //     });
    // },

    // 需求人数校验
    getUsernumval(taskNum) {
      if (taskNum <= "0") {
        this.$message.error("需求人数必须大于0");
        return false;
      } else {
      }
    },

    // 任务类型列表
    getTaskTypeList() {
      let arg = {
        id: "1"
      };
      getTaskTypeTree(arg).then(response => {
        response.data.data.treeList.forEach(item => {
          item.children.forEach(item1 => {
            const addnew = {
              value: item1.taskTypeId,
              label: item1.taskTypeName
            };
            this.taskTypeList1.push(addnew);
          });
        });
      });
    },

    // 初始化页面
    getList(page, params) {
      this.tableLoading = true;
      getScorePackagePage(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
            packageType1: "4", // 必传固定值
            packageType2: "2" // 必传固定值
          },
          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;
        });
    },

    // 新增-展示弹窗
    async addData() {
      this.showTit = "新增";
      this.addDialog = true;
      let res = await getPackageSn();
      this.packageSn = res.data.data;
      this.addForm.packageSn = res.data.data;
      setTimeout(() => {
        if (this.addForm.subjectLocation === "REN_LI_JIA") {
          this.$message({
            message:
              "人力家单笔结算额不得超过5万元，请注意发包积分值，避免浪费积分",
            type: "warning"
          });
        }
      }, 300);
    },
    // 新增-确认按钮
    sureBtn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.addForm.packageType1 = "4";
          this.addForm.packageType2 = "2";
          this.addForm.packageUserScope = "1";
          this.addForm.typeid = "4";
          // this.addForm.packageSn = this.packageSn;

          if (this.showTit == "新增") {
            addWmScorePackage(this.addForm)
              .then(response => {
                this.$message.success(response.data.data);
                this.getList(this.page);
                this.addDialog = false;
                this.addForm = {};
                this.buttonLoading = false;
              })
              .catch(() => {
                this.buttonLoading = false;
              });
          } else {
            // 编辑保存
            saveById(this.addForm)
              .then(response => {
                this.$message.success("编辑成功");
                this.getList(this.page);
                this.addDialog = false;
                this.addForm = {};
                this.buttonLoading = false;
                this.addForm.typeid = "4";
              })
              .catch(() => {
                this.buttonLoading = false;
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 编辑
    updateSettle(row) {
      this.showTit = "编辑";
      this.addDialog = true;

      // 回显数据
      let arg = {
        id: row.id
      };
      searchById(arg)
        .then(response => {
          this.addForm = response.data.data;
        })
        .catch(() => {
          console.log("请求异常");
        });
    },

    // 接单审批
    receiveApproval(row) {
      this.$router.push({
        path:
          "/admin/assignPoints/settlement/manList?id=" +
          row.id +
          "&type=jdspType"
      });
    },

    // 举证上传
    proofTopload(row) {
      // this.$router.push({
      //   path: "/admin/assignPoints/settlement/proofUpload?id=" + row.id,
      // });

      this.$router.push({
        path:
          "/admin/assignPoints/settlement/manList?id=" +
          row.id +
          "&type=zjlscType"
      });
    },
    // 导出
    exportBtn(row) {
      this.exportDig = true;
      this.checkRow = row;
    },
    // 导出汇总报告
    taskExport() {
      this.taskExportLoading = true;
      let row = this.checkRow;
      var obj = {
        scorePackageDrugId: row.id,
        exportType: 1
      };
      exportZbInfoJs(obj)
        .then(response => {
          if (undefined == response.data || undefined == response.data.data) {
            this.$message.error("导出失败");
            return false;
          }
          let obj = response.data.data;
          let a = document.createElement("a");
          a.href = obj.url; // 这里的请求方式为get，如果需要认证，接口上需要带上token
          a.click();
          this.$message.success("导出导出汇总报告成功");
          this.taskExportLoading = false;
        })
        .catch(() => {
          this.taskExportLoading = false;
        });
    },
    close() {
      this.settleTableVisible = false;
      this.$refs.form.resetFields();
    },

    // 导出报告详情
    taskExportInfo() {
      this.taskExportInfoLoading = true;
      let row = this.checkRow;
      var obj = {
        scorePackageDrugId: row.id,
        exportType: 2
      };
      exportZbInfoJs(obj)
        .then(response => {
          if (undefined == response.data || undefined == response.data.data) {
            this.$message.error("导出失败");
            return false;
          }
          let obj = response.data.data;
          let a = document.createElement("a");
          a.href = obj.url; // 这里的请求方式为get，如果需要认证，接口上需要带上token
          a.click();
          this.$message.success("导出报告详情成功");
          this.taskExportInfoLoading = false;
        })
        .catch(() => {
          this.taskExportInfoLoading = false;
        });
    },
    // 删除
    delBtn(row) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.tableLoading = true;
          updateWmScorePackage({
            id: row.id,
            delFlag: 1
          })
            .then(() => {
              this.getList(this.page);
              this.tableLoading = false;
            })
            .catch(() => {
              this.tableLoading = false;
            });
        })
        .catch(() => {
          //console.log("请求异常");
        });
    },
    // 结算
    settlement(row) {
      this.$confirm("您正在进行结算操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.tableLoading = true;
          updateWmScorePackage({
            id: row.id,
            settleFlag: 1,
            settleStatus: 9,
            scorePackageStatus: 5,
            packageFinishStatus: 1
          })
            .then(() => {
              this.getList(this.page);
              this.$message.success("结算成功");
              this.tableLoading = false;
            })
            .catch(() => {
              this.tableLoading = false;
            });
        })
        .catch(() => {
          //console.log("请求异常");
        });
    },
    // 查看
    toView(row) {
      this.$router.push({
        path:
          "/admin/assignPoints/settlement/manList?id=" +
          row.id +
          "&type=lookType"
      });
    },
    // 查询
    searchVal(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    // 分页查询
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },

    // 隐藏弹出窗
    handleClose() {
      this.addForm = {};
      this.addDialog = false;
      this.showTit = "";
      this.addForm.typeid = "4";
    },
    cancelBtn() {
      this.addForm = {};
      this.addDialog = false;
      this.showTit = "";
      this.addForm.typeid = "4";
    },
    //以下是结算的方法
    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;
    },
    discountChange(e) {
      let value = e.discount.toString();
      value = value.replace(/[^\d.\-]/g, ""); //清除"数字"和"." "-"负号以外的字符
      value = value.replace(/^\./g, ""); //验证第一个字符是数字
      value = value.replace(/\.{2,}/g, ""); //只保留第一个, 清除多余的
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数

      e.discount = value;
      e.settleAmount = (Number(this.score) * Number(value)).toFixed(2);
    },
    discountInput(e) {
      let value = e.discount;
      // if (value) {
      //
      // } else {
      //     e.discount = 0
      //     e.settleAmount = 0
      // }
      value = value.replace(/[^\d.\-]/g, ""); //清除"数字"和"." "-"负号以外的字符
      value = value.replace(/^\./g, ""); //验证第一个字符是数字
      value = value.replace(/\.{2,}/g, ""); //只保留第一个, 清除多余的
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
      // if (Number(value) > 2) {
      //   e.discount = 1
      //   this.$message.warning('折扣不能超过2');
      //   return
      // }
      // e.discount = Number(value)
      e.discount = value;
      e.settleAmount = (Number(this.score) * Number(value)).toFixed(2);
    },
    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 {
      }
    },
    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;
    },
    reIssue(id) {
      console.log(id);
      this.$confirm("此操作将不可撤回,确认重新结算?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.buttonLoading = true;
        const args = {
          id: id
        };
        settleReIssue(args)
          .then(response => {
            this.$message.warning(response.data.msg);
            this.buttonLoading = false;
          })
          .catch(() => {
            // this.hideDialog();
            this.buttonLoading = false;
          });
      });
    },
    hideDialog() {
      this.settleTableVisible = false;
      this.form = {};
      this.gridData = [];
      this.getList(this.page, this.searchForm);
      // this.$refs.form.resetFields();
    },
    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();
            });
        }
      });
    },
    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();
        });
    }
    //以上是结算的方法
  }
};
</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;
  }
}
</style>

<style>
/*.treeBox {*/
/*  width: 100%;*/
/*  height: 200px;*/
/*  border: 1px solid #dcdfe6;*/
/*  overflow-y: scroll;*/
/*  overflow-x: hidden;*/
/*  border-radius: 10px;*/
/*}*/
.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);
}
</style>
