<template>
  <basic-container>
    <div>
      <avue-crud
        :data="tableData"
        :option="optionData"
        :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="taskTypes" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="viewDetail(scope.row, scope.index)"
            >查看
          </el-button>
        </template>

        <template slot="menu" slot-scope="scope">
          <template
            v-if="scope.row.enableType == '0' || scope.row.enableType == '2'"
          >
            <el-button
              type="text"
              size="small"
              icon="el-icon-tickets"
              v-show="
                scope.row.enableFlag != '1' &&
                  scope.row.typeid == '4' &&
                  scope.row.yjddsh != null &&
                  scope.row.yjddsh > 0
              "
              @click="receiveApproval(scope.row, scope.index)"
              >接单审批
            </el-button>

            <el-button
              style="color: #56b088"
              type="text"
              size="small"
              icon="el-icon-document-checked"
              v-show="scope.row.dsh != null && scope.row.dsh != '0'"
              @click="taskReview(scope.row, scope.index)"
              >任务审核
            </el-button>

            <el-button
              type="text"
              size="small"
              icon="el-icon-setting"
              v-show="
                scope.row.scorePackageStatus == null ||
                  scope.row.scorePackageStatus <= 2
              "
              @click="editBtn(scope.row, scope.index)"
              >编辑
            </el-button>

            <!--          <el-button-->
            <!--            type="text"-->
            <!--            size="small"-->
            <!--            icon="el-icon-close"-->
            <!--            :disabled="scope.row.ytj > 0"-->
            <!--            @click="delBtn(scope.row, scope.index)"-->
            <!--            >删除-->
            <!--          </el-button>-->

            <el-button
              type="text"
              size="small"
              icon="el-icon-folder-delete"
              @click="suspendBtn(scope.row, scope.index)"
              v-show="
                (scope.row.settleFlag == null || scope.row.settleFlag == '0') &&
                  scope.row.enableType == 0 &&
                  (scope.row.shtg == 0 || scope.row.shtg == null)
              "
              >终止
            </el-button>

            <el-button
              type="text"
              size="small"
              icon="el-icon-finished"
              v-show="
                (scope.row.settleFlag == null || scope.row.settleFlag == '0') &&
                  scope.row.packageFinishStatus == '1' &&
                  scope.row.typeid == '4'
              "
              @click="settleById(scope.row)"
              >结算
            </el-button>

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

      <el-dialog
        :title="showTit"
        :visible.sync="showDialog"
        width="60%"
        @close="handleClose"
        center
      >
        <el-form
          :model="pointsForm"
          :rules="rules"
          ref="pointsForm"
          label-width="138px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="积分包名称" prop="scorePackageName">
                <el-input v-model="pointsForm.scorePackageName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="个人预计包值" prop="userScore">
                <el-input
                  autocomplete="off"
                  v-model="pointsForm.userScore"
                  onkeyup="value=value.replace(/[^\d]/g,'')"
                ></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="pointsForm.taskNum"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="需求人数" v-show="showUsernum">
                <el-input
                  v-model="pointsForm.userNum"
                  onkeyup="value=value.replace(/[^\d]/g,'')"
                  @input="getUsernumval(pointsForm.userNum)"
                ></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="pointsForm.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="pointsForm.userList"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in receivingObject"
                    :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="接单对象范围" prop="packageUserScope">
                <el-select
                  style="width: 100%"
                  v-model="pointsForm.packageUserScope"
                  placeholder="请选择"
                  :disabled="userScopeAble"
                  @change="$forceUpdate()"
                >
                  <el-option
                    v-for="item in objectScopelist"
                    :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="结算渠道" prop="subjectLocation">
                <el-select
                  v-model="pointsForm.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="24">
              <el-form-item label="有效任务类型" prop="taskTypeList">
                <div class="treeBox">
                  <el-tree
                    ref="tree"
                    :data="pointsForm.taskTypeList"
                    :filter-node-method="filterNode"
                    :default-checked-keys="checkedDsScope"
                    show-checkbox
                    default-expand-all
                    node-key="taskTypeId"
                    :props="defaultProps"
                    @check-change="getNodeData"
                  >
                  </el-tree>
                </div>
              </el-form-item>
            </el-col>
          </el-row> -->

          <el-row>
            <el-col :span="24">
              <el-form-item label="描述：" prop="description">
                <el-input
                  type="textarea"
                  v-model="pointsForm.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('pointsForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 导出弹窗 -->
      <el-dialog
        title="导出"
        :visible.sync="exportDig"
        width="30%"
        :close-on-click-modal="false"
        center
      >
        <!-- 第一次导出 -->
        <template>
          <div class="down-item">
            <span>word格式：</span>
            <template
              v-if="checkRow && checkRow.reportOpt.status === 'NOT_GENERATE'"
            >
              <el-button
                class="first"
                @click="taskExport('word')"
                :loading="wordLoading"
                >生成报告</el-button
              >
            </template>
            <template
              v-else-if="checkRow && checkRow.reportOpt.status === 'GENERATING'"
            >
              <el-button class="first" :loading="true">报告生成中...</el-button>
            </template>
            <template
              v-else-if="
                checkRow &&
                  (checkRow.reportOpt.status === 'GENERATED' ||
                    checkRow.reportOpt.status === 'ERROR')
              "
            >
              <el-button @click="taskExport('word')">重新导出</el-button>
              <el-button
                @click="downloadTask('word')"
                v-if="checkRow.reportOpt.status === 'GENERATED'"
                >下载报告</el-button
              >
              <el-button
                disabled
                :title="checkRow.reportOpt.errorMsg"
                v-else-if="checkRow.reportOpt.status === 'ERROR'"
                >导出失败</el-button
              >
            </template>
            <div class="title-msg">
              <p v-if="checkRow && checkRow.reportOpt.status === 'GENERATED'">
                下载截止日期：{{ checkRow.reportOpt.ttl }}
              </p>
              <p v-if="checkRow && checkRow.reportOpt.status === 'ERROR'">
                本次导出失败：{{ checkRow.reportOpt.errorMsg }}
              </p>
            </div>
          </div>
          <div class="down-item">
            <span>excel格式：</span>
            <template
              v-if="
                checkRow && checkRow.excelReportOpt.status === 'NOT_GENERATE'
              "
            >
              <el-button
                class="first"
                @click="taskExport('excel')"
                :loading="excelLoading"
                >生成报告</el-button
              >
            </template>
            <template
              v-if="checkRow && checkRow.excelReportOpt.status === 'GENERATING'"
            >
              <el-button class="first" :loading="true">报告生成中...</el-button>
            </template>
            <template
              v-else-if="
                checkRow &&
                  (checkRow.excelReportOpt.status === 'GENERATED' ||
                    checkRow.excelReportOpt.status === 'ERROR')
              "
            >
              <el-button @click="taskExport('excel')">重新导出</el-button>
              <el-button
                @click="downloadTask('excel')"
                v-if="checkRow.excelReportOpt.status === 'GENERATED'"
                >下载报告</el-button
              >
              <el-button
                disabled
                :title="checkRow.excelReportOpt.errorMsg"
                v-else-if="checkRow.excelReportOpt.status === 'ERROR'"
                >导出失败</el-button
              >
            </template>
            <div class="title-msg">
              <p
                v-if="
                  checkRow && checkRow.excelReportOpt.status === 'GENERATED'
                "
              >
                下载截止日期：{{ checkRow.excelReportOpt.ttl }}
              </p>
              <p v-if="checkRow && checkRow.excelReportOpt.status === 'ERROR'">
                本次导出失败：{{ checkRow.excelReportOpt.errorMsg }}
              </p>
            </div>
          </div>
        </template>
        <span slot="footer" class="dialog-footer">
          注意： 1.报告将于24小时之内生成完毕，请注意下载。<br />
          <i style="margin-left:62px"></i
          >2.报告汇总为封面+任务数据汇总+任务列表明细。
          <br />
          <i style="margin-left:10px"></i>3.报告详情为每条任务的任务详情+图片。
        </span>
      </el-dialog>

      <!-- 中止任务 -->
      <el-dialog
        title="终止任务"
        :visible.sync="enableFlagDig"
        width="50%"
        center
      >
        <el-form
          :model="enableForm"
          :rules="enableRule"
          ref="enableForm"
          label-width="150px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="请选择积分收回方式" prop="enableFlag">
                <el-radio-group v-model="enableForm.enableFlag">
                  <el-radio label="1">全部收回</el-radio>
                  <el-radio label="2">剩余收回</el-radio>
                </el-radio-group>
              </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" @click="enableFlagBtn('enableForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 表单-查看有效任务类型 -->
      <el-dialog
        title="有效任务类型"
        :visible.sync="taskTypedialog"
        width="50%"
        center
        :before-close="handleClose"
      >
        <div style="text-align:center">
          <span>{{ taskTypes }}</span>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelBtn">取 消</el-button>
        </span>
      </el-dialog>

      <!--      结算弹出框-->
      <el-dialog
        title="结算"
        :close-on-click-modal="false"
        @close="hideDialog"
        :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>
          <br />
          <el-form-item label="描述：" prop="description" class="settle-desc">
            <el-input
              :autosize="{ minRows: 3, maxRows: 10 }"
              maxlength="200"
              show-word-limit
              type="textarea"
              v-model="form.description"
            ></el-input>
          </el-form-item>
          <div class="separator">结算信息</div>
          <el-form-item
            label="结算渠道"
            prop="subjectLocation"
            class="settle-label"
          >
            <el-select
              v-model="form.subjectLocation"
              placeholder="请选择结算渠道"
              @change="subTypeChange"
            >
              <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-form-item
            label="发票类目"
            prop="invoiceCategory"
            class="settle-label"
          >
            <el-select
              @change="invoiceCategoryChange"
              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 ||
                      scope.row.settleNoteStatus === 2)
                "
                v-model="scope.row.discount"
                placeholder="请输入折扣"
                @change="discountChange(scope.row)"
                @input="discountInput(scope.row)"
              ></el-input>
              <span v-else>{{ 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 ||
                      scope.row.settleNoteStatus === 2)
                "
                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 { allotPointsData } from "@/const/crud/assignPoints/commonUse/index";
import {
  getScorePackagePage,
  getRelationScoreList,
  typeid,
  objectScope1,
  showDescription,
  addWmScorePackage,
  packageUserScope,
  exportZbReport,
  exportZbReportExcel,
  updateEnable,
  updateWmScorePackage,
  getScorePackagePageById,
  getAllParentDept,
  getTaskTypeTree,
  editData
} from "@/api/assignPoints/currency/index";
import {
  listPackageSettleList,
  settleById,
  settleSave,
  settleIssue,
  settleReIssue,
  settleSubmit
} from "@/api/settle/settle";
import { getSubSelect } from "@/api/admin/deptSub";
import { invoiceDictMap } from "@/const/constants/invoice";
import { getDictType } from "@/api/common";
import { SUBJECT_TYPE_MAP } from "@/const/auth";

export default {
  name: "allotPoints",
  data() {
    // 自定义校验-个人预计包值
    var userScorepass = (rule, value, callback) => {
      if (value <= 0) {
        callback(this.$message.error("个人预计包值必须大于0"));
      } else {
        callback();
      }
    };
    // 自定义校验-个人包任务个数
    var taskNumpass = (rule, value, callback) => {
      if (value <= 0) {
        callback(this.$message.error("个人包任务个数值必须大于0"));
      } else {
        callback();
      }
    };

    return {
      subList: [],
      optionData: allotPointsData,
      tableData: [],
      showTit: "",
      showDialog: false,
      pointsForm: {
        subjectLocation: "",
        scorePackageName: "",
        packageUserScope: "1",
        userList: [],
        taskTypeList: [
          {
            taskTypeId: "28",
            type: "2",
            taskTypeName: "通用"
          }
        ],
        userNum: "",
        userScore: "",
        taskNum: "",
        packageType1: "3",
        packageType2: "1",
        description: ""
      },
      rules: {
        scorePackageName: [
          { required: true, message: "请输入积分包名称", trigger: "blur" }
        ],
        score: [{ required: true, message: "请输入积分包值", trigger: "blur" }],
        packageUserScope: [
          { required: true, message: "请选择接单对象范围", trigger: "change" }
        ],
        typeid: [
          { required: true, message: "请选择接单对象类型", trigger: "change" }
        ],
        userScore: [
          {
            required: true,
            message: "",
            trigger: "blur",
            validator: userScorepass
          }
        ],
        taskNum: [
          {
            required: true,
            message: "",
            trigger: "blur",
            validator: taskNumpass
          }
        ]
        // subType: [
        //     {required: true, message: "请选择结算渠道", trigger: "blur"}
        // ]
      },

      page: {
        total: 20,
        pageSize: 10,
        pagerCount: 5
      },
      exportDig: false,
      wordLoading: false,
      excelLoading: false,
      taskExportLoading: false,
      taskExportInfoLoading: false,
      tableLoading: false,
      userScopeAble: false,
      showPackage: true,
      objectScopelist: [],
      idVal: "",
      checkRow: null,
      suspendData: null,
      enableFlagDig: false,
      enableForm: {},
      enableRule: {
        enableFlag: [
          { required: true, message: "请选择积分回收方式", trigger: "change" }
        ]
      },
      searchForm: {},

      typeidList: [],
      receivingObject: [],
      // 有效任务类型展示tree
      defaultProps: {
        children: "children",
        label: "taskTypeName"
      },
      // checkedDsScope: [],
      taskTypedialog: false, // 有效任务类型弹窗
      taskTypes: "",
      showUsernum: true,
      settleTableVisible: false,
      buttonLoading: false,
      form: {},
      gridData: [],
      settleButtonShow: false,
      settleRules: {
        invoiceCategory: [
          { required: true, message: "请选择发票类目", trigger: "blur" }
        ],
        subjectLocation: [
          { required: true, message: "请选择结算渠道", trigger: "blur" }
        ]
      },
      invoiceList: [],
      renlijia_invoice_dict: [], // 发票类目-人力加
      tax_helper_invoice_dict: [], // 发票类目-税邦云
      olading_invoice_dict: [], // 发票类目-自由职家
      yee_invoice_dict: [], // 发票类目-易联
      olading_jinyuan_invoice_dict: [], // 发票类目-金园数科
      olading_henan_invoice_dict: [],
      olading_zhaoyu_invoice_dict: [],
      zheng_qi_zhi_xing_invoice_dict: [],
      hui_qi_yun_invoice_dict: [],
      zhong_yi_yun_invoice_dict: [],
      zhong_zhi_invoice_dict: [],
      qi_fu_invoice_dict: [],
      shen_zhen_ren_cai_invoice_dict: [],
      yi_ma_invoice_dict: [],
      xin_shi_yi_invoice_dict: [],
      he_chuang_zhong_zhi_invoice_dict: [],
      he_chuang_ren_cai_yun_invoice_dict: [],
      invoiceList0: [
        { value: 3, label: "现代服务*技术咨询服务费" },
        { value: 7, label: "现代服务*推广服务费" },
        { value: 4, label: "现代服务*其他咨询服务费" },
        { value: 5, label: "现代服务*现场辅助服务费" }
      ],
      invoiceList1: [
        { value: 1, label: "推广服务费" },
        { value: 2, label: "营销服务费" },
        { value: 3, label: "信息服务费" }
      ]
    };
  },
  mounted() {
    this.showUserScope(); // 接单对象范围
    this.typeidShow(); // 接单对象类型-展示
    this.showObjectscope(); //接单对象
    this.showSubSelect();
    this.getInvoiceDict();
  },
  methods: {
    addSubTypeChange(val) {
      this.$message.closeAll();
      if (val === "REN_LI_JIA") {
        this.$message({
          message:
            "人力家单笔结算额不得超过5万元，请注意发包积分值，避免浪费积分",
          type: "warning"
        });
      }
    },
    getInvoiceDict() {
      getDictType({ type: "renlijia_invoice" }).then(res => {
        this.renlijia_invoice_dict = res.data.data;
      });
      getDictType({ type: "tax_helper_invoice" }).then(res => {
        this.tax_helper_invoice_dict = res.data.data;
      });
      getDictType({ type: "olading_invoice" }).then(res => {
        this.olading_invoice_dict = res.data.data;
      });
      getDictType({ type: "yee_invoice" }).then(res => {
        this.yee_invoice_dict = res.data.data;
      });
      getDictType({ type: "olading_jinyuan_invoice" }).then(res => {
        this.olading_jinyuan_invoice_dict = res.data.data;
      });
      getDictType({ type: "olading_henan_invoice" }).then(res => {
        this.olading_henan_invoice_dict = res.data.data;
      });
      getDictType({ type: "olading_zhaoyu_invoice" }).then(res => {
        this.olading_zhaoyu_invoice_dict = res.data.data;
      });
      getDictType({ type: "zheng_qi_zhi_xing_invoice" }).then(res => {
        this.zheng_qi_zhi_xing_invoice_dict = res.data.data;
      });
      getDictType({ type: "hui_qi_yun_invoice" }).then(res => {
        this.hui_qi_yun_invoice_dict = res.data.data;
      });
      getDictType({ type: "zhong_yi_yun_invoice" }).then(res => {
        this.zhong_yi_yun_invoice_dict = res.data.data;
      });
      getDictType({ type: "zhongzhi_invoice" }).then(res => {
        this.zhong_zhi_invoice_dict = res.data.data;
      });
      getDictType({ type: "qifu_invoice" }).then(res => {
        this.qi_fu_invoice_dict = res.data.data;
      });
      getDictType({ type: "shenzhenrencai_invoice" }).then(res => {
        this.shen_zhen_ren_cai_invoice_dict = res.data.data;
      });
      getDictType({ type: "yi_ma_invoice" }).then(res => {
        this.yi_ma_invoice_dict = res.data.data;
      });
      getDictType({ type: "xinshiyi_invoice" }).then(res => {
        this.xin_shi_yi_invoice_dict = res.data.data;
      });
      getDictType({ type: "hechuang_zhongzhi_invoice" }).then(res => {
        this.he_chuang_zhong_zhi_invoice_dict = res.data.data;
      });
      getDictType({ type: "hechuang_rencaiyun_invoice" }).then(res => {
        this.he_chuang_ren_cai_yun_invoice_dict = res.data.data;
      });
    },
    subTypeChange(val) {
      this.invoiceList = [];
      delete this.form.invoiceCategory;
      delete this.form.categoryName;
      const selectedSubType = this.subList.filter(
        ele => ele.subjectLocation === val
      );
      this.invoiceList = this[SUBJECT_TYPE_MAP[val] + "_invoice_dict"].filter(
        ele => {
          if (
            selectedSubType[0].subjectInvoiceCategory &&
            selectedSubType[0].subjectInvoiceCategory
              .split(",")
              .includes(ele.value)
          ) {
            return ele;
          }
        }
      );
    },
    invoiceCategoryChange(e) {
      let item = this.invoiceList.find(item => item.value === e);
      this.form.categoryName = item.label;
    },
    async showSubSelect() {
      const res1 = await getSubSelect();
      this.subList = res1.data.data;
      if (!this.subList) return;
      this.pointsForm.subjectLocation = this.subList[0].subjectLocation;
    },
    // 接单对象类型-展示
    typeidShow() {
      typeid().then(response => {
        response.data.data.forEach(item => {
          const addnew = {
            value: item.value,
            label: item.label
          };
          this.typeidList.push(addnew);
        });
      });
    },

    // 接单对象展示
    showObjectscope() {
      objectScope1().then(response => {
        response.data.data.forEach(item => {
          const addnew = {
            value: item.id,
            label: item.realname
          };
          this.receivingObject.push(addnew);
        });
      });
    },

    // 接单对象类型-判断是否显示接单对象
    async typeidChange(id) {
      this.idVal = id;
      this.pointsForm.subjectLocation = "";
      if (id == "3") {
        this.pointsForm.subjectLocation = "";
        this.pointsForm.packageUserScope = "1";
        this.userScopeAble = true;
        this.showPackage = true;
        this.showUsernum = false;
        this.userNumval = "";
        this.pointsForm.userNum = "";
        this.pointsForm.userList = [];
        if (this.pointsForm.userList == []) {
          this.$message.warning("请选择接单对象");
        }
      } else {
        // this.pointsForm.packageUserScope = ''
        await this.showSubSelect();
        this.userScopeAble = false;
        this.showUsernum = true;
        this.showPackage = false;
        this.userNumval = "";
        this.pointsForm.userNum = "";
        this.pointsForm.userList = [];
        if (this.pointsForm.userNum == "") {
          this.$message.warning("请填写需求人数");
          setTimeout(() => {
            this.$message.closeAll();
            if (this.pointsForm.subjectLocation === "REN_LI_JIA") {
              this.$message({
                message:
                  "人力家单笔结算额不得超过5万元，请注意发包积分值，避免浪费积分",
                type: "warning"
              });
            }
          }, 1000);
        } else {
          if (this.pointsForm.subjectLocation === "REN_LI_JIA") {
            this.$message({
              message:
                "人力家单笔结算额不得超过5万元，请注意发包积分值，避免浪费积分",
              type: "warning"
            });
          }
        }
      }
    },

    // 需求人数校验
    getUsernumval(userNum) {
      this.userNumval = userNum;
      if (userNum <= "0") {
        this.$message.error("需求人数必须大于0");
        this.buttonLoading = false;
        return false;
      }
    },
    // 接单对象范围-默认展示
    showUserScope() {
      packageUserScope().then(response => {
        response.data.data.forEach(item => {
          const addnew = {
            value: item.value,
            label: item.label
          };
          this.objectScopelist.push(addnew);
        });
      });
    },

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

    close() {
      this.getList(this.page, this.searchForm);
    },

    // 查询
    searchVal(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },

    // 有效任务类型选中值
    chooseItem(value) {
      this.typeData = [];
      for (let i = 0; i < value.length; i++) {
        this.typeData.push({
          type: value[i]
        });
      }
    },

    // 新增按钮-展示弹窗
    addData() {
      this.showTit = "新增";
      this.showDialog = true;
      this.showPackage = true;
      this.buttonLoading = false;
      this.showUsernum = true;
    },
    // 编辑
    editBtn(row) {
      this.userNumval = row.userNum;
      this.idVal = row.typeid;

      this.showTit = "编辑";
      this.showDialog = true;
      if (row.typeid == "3") {
        this.showPackage = true;
        this.showUsernum = false;
      } else {
        this.showPackage = false;
        this.showUsernum = true;
      }
      let arg = {
        id: row.id
      };
      getScorePackagePageById(arg).then(response => {
        this.pointsForm = response.data.data;
      });
    },

    // 弹窗-确定按钮
    sureBtn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          (this.pointsForm.packageType1 = "3"), // 必传固定值
            (this.pointsForm.packageType2 = "1"); // 必传固定值
          if (this.idVal == "3") {
            if (this.pointsForm.userList.length == 0) {
              this.$message.error("接单对象不能为空");
              this.buttonLoading = false;
              return false;
            }
          } else {
            if (this.userNumval <= "0" || this.userNumval == "") {
              this.$message.error("需求人数必须大于0");
              this.buttonLoading = false;
              return false;
            }
          }

          if (this.showTit == "新增") {
            // 新增
            addWmScorePackage(this.pointsForm)
              .then(response => {
                this.$message.success(response.data.data);
                this.getList(this.page);
                this.showDialog = false;
                this.pointsForm = {};
                this.buttonLoading = false;
              })
              .catch(() => {
                this.buttonLoading = false;
                // this.showDialog = false;
                // this.pointsForm= {}
              });
          } else {
            // 编辑
            editData(this.pointsForm)
              .then(response => {
                this.$message.success("修改成功");
                this.getList(this.page);
                this.showDialog = false;
                this.pointsForm = {};
                this.buttonLoading = false;
              })
              .catch(() => {
                this.buttonLoading = false;
                // this.showDialog = false;
                // this.pointsForm= {
                //    userList: [],
                //    taskTypeList:[
                //      {
                //        taskTypeId:"28",
                //        type: "2",
                //        taskTypeName: "通用",
                //
                //      }
                //    ],
                //    userNum: "",
                //    userScore: "",
                //    taskNum: "",
                //    packageType1:"3",
                //    packageType2: "1"
                //  }
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 终止
    suspendBtn(row) {
      this.$router.push({
        path:
          "/admin/assignPoints/commonUse/approval?id=" +
          row.id +
          "&type=1" +
          "&ytj=" +
          row.ytj
      });
      // this.enableFlagDig = true;
      // this.suspendData = row;
    },
    // 中止确认按钮
    enableFlagBtn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let args = {
            enableType: this.enableForm.enableFlag,
            id: this.suspendData.id
          };
          updateEnable(args).then(response => {
            this.$message.success(response.data.data);
            this.getList(this.page);
            this.enableFlagDig = false;
            this.enableForm = {};
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 接单审批
    receiveApproval(row) {
      this.$router.push({
        path: "/admin/assignPoints/commonUse/approval?id=" + row.id
      });
    },

    // 任务审核
    taskReview(row) {
      this.$router.push({
        path:
          "/admin/assignPoints/commonUse/taskAudit?id=" +
          row.id +
          "&type=taskAudit" +
          "&taskStatus=2"
      });
    },

    // 删除
    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,
            scorePackageStatus: 5,
            settleStatus: 9
          })
            .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/commonUse/taskAudit?id=" + row.id + "&type=look"
      });
    },

    // 导出
    exportBtn(row) {
      this.exportDig = true;
      this.checkRow = row;
    },

    // 导出汇总报告
    taskExport(type) {
      let row = this.checkRow;
      var obj = {
        scorePackageDrugId: row.id,
        exportType: 1
      };
      if (type === "word") {
        this.wordLoading = true;
        exportZbReport(obj)
          .then(response => {
            if (undefined == response.data || undefined == response.data.data) {
              this.$message.error("导出失败");
              return false;
            }
            this.$message.success(response.data.data);
            this.exportDig = false;
            this.getList(this.page);
            this.wordLoading = false;
          })
          .catch(() => {
            this.wordLoading = false;
          });
      } else if (type === "excel") {
        this.excelLoading = true;
        exportZbReportExcel(obj)
          .then(response => {
            if (undefined == response.data || undefined == response.data.data) {
              this.$message.error("导出失败");
              return false;
            }
            this.$message.success(response.data.data);
            this.exportDig = false;
            this.getList(this.page);
            this.excelLoading = false;
          })
          .catch(() => {
            this.excelLoading = false;
          });
      }
    },
    downloadTask(type) {
      let latestUrl;
      if (type === "word") {
        latestUrl = this.checkRow.reportOpt.latestUrl;
      } else if (type === "excel") {
        latestUrl = this.checkRow.excelReportOpt.latestUrl;
      }
      let a = document.createElement("a");
      a.href = latestUrl;
      a.click();
      this.$message.success("导出汇总报告成功");
      this.exportDig = false;
    },

    // 导出报告详情
    taskExportInfo() {
      this.taskExportInfoLoading = true;
      let row = this.checkRow;
      var obj = {
        scorePackageDrugId: row.id,
        exportType: 2
      };
      exportZbReport(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;
        });
    },
    // 隐藏弹出窗
    cancelBtn() {
      this.showDialog = false;
      this.enableFlagDig = false;
      this.taskTypedialog = false;
      this.taskTypes = "";
      this.enableForm = {};
      this.pointsForm = {
        userList: [],
        taskTypeList: [
          {
            taskTypeId: "28",
            type: "2",
            taskTypeName: "通用"
          }
        ],
        userNum: "",
        userScore: "",
        taskNum: "",
        packageType1: "3",
        packageType2: "1"
      };
      this.getList(this.page, this.searchForm);
    },

    handleClose() {
      this.showDialog = false;
      this.enableFlagDig = false;
      this.taskTypedialog = false;
      this.taskTypes = "";
      this.enableForm = {};
      this.pointsForm = {
        userList: [],
        taskTypeList: [
          {
            taskTypeId: "28",
            type: "2",
            taskTypeName: "通用"
          }
        ],
        userNum: "",
        userScore: "",
        taskNum: "",
        packageType1: "3",
        packageType2: "1"
      };
      this.getList(this.page, this.searchForm);
    },

    // 表格-查看有效任务类型
    viewDetail(row) {
      this.taskTypes = row.taskTypes == null ? "无" : row.taskTypes;
      this.taskTypedialog = true;
    },
    // 分页查询
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    //以下是结算的方法
    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"); //只能输入两个小数

        let total = Number(this.score) * 1.2;
        let total1 = Number(this.score) * 0.8;
        // if (Number(value) > total) {
        //   e.settleAmount = this.score
        //   e.discount = 1
        //   this.$message.warning('折扣不能超过2');
        //   return
        // }
        // if (Number(value) < total1) {
        //   e.settleAmount = this.score
        //   e.discount = 1
        //   this.$message.warning('折扣不能低于0.5');
        //   return
        // }
        let discount = (Number(value) / Number(this.score)).toFixed(2);

        e.settleAmount = value;
        e.discount = discount;
      } else {
        e.settleAmount = 0;
        e.discount = 0;
      }
    },
    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"); //只能输入两个小数
      let discount = 0;
      if (value) {
        discount = (Number(value) / Number(this.score)).toFixed(2);
      }

      e.settleAmount = value;
      e.discount = discount;
    },
    reIssue(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.8) ||
              Number(item.discount) > Number(1.2)
            ) {
              this.$message.error(
                "第" + parseInt(i + 1) + "行，折扣应介于0.8~1.2之间"
              );
              return false;
            }
          }
          const args = {
            id: this.id,
            invoiceCategory: this.form.invoiceCategory,
            categoryName: this.form.categoryName,
            description: this.form.description,
            subjectLocation: this.form.subjectLocation,
            notes: this.gridData
          };
          if (
            args.subjectLocation === "REN_LI_JIA" &&
            args.notes[0].settleAmount > 50000
          ) {
            this.$message.error("人力家单笔结算额不得超过5万元");
            return;
          }
          this.buttonLoading = true;
          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.8) ||
              Number(item.discount) > Number(1.2)
            ) {
              this.$message.error(
                "第" + parseInt(i + 1) + "行，折扣应介于0.8~1.2之间"
              );
              return false;
            }
          }
          const args = {
            id: this.id,
            invoiceCategory: this.form.invoiceCategory,
            categoryName: this.form.categoryName,
            description: this.form.description,
            subjectLocation: this.form.subjectLocation,
            notes: this.gridData
          };
          if (
            args.subjectLocation === "REN_LI_JIA" &&
            args.notes[0].settleAmount > 50000
          ) {
            this.$message.error("人力家单笔结算额不得超过5万元");
            return;
          }
          this.buttonLoading = true;
          settleSubmit(args)
            .then(response => {
              if (response.data.code === 0) {
                this.$message.success("提交成功");
              }
              this.hideDialog();
              this.buttonLoading = false;
            })
            .catch(() => {
              this.buttonLoading = false;
              // this.hideDialog();
            });
        }
      });
    },
    settleById(row) {
      if (!this.subList) {
        this.$message.error("当前机构未配置结算渠道");
        return;
      } else {
        if (row.subjectLocation) {
          let sub = this.subList.find(item => {
            return item.subjectLocation === row.subjectLocation;
          });
          if (!sub) {
            this.$message.error("当前机构结算渠道发生变化，请联系管理员处理");
            return;
          }
        }
      }
      this.settleButtonShow = true;
      const args = { id: row.id };
      settleById(args)
        .then(response => {
          const res = response.data.data;
          this.gridData = res.notes;
          this.form = res.wsp;
          this.subTypeChange(this.form.subjectLocation);
          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;
  }
}

.settle-desc {
  width: 80%;

  ::v-deep textarea {
    width: 600px;
  }
}

.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;
  }
}

.generating {
  color: #1e90ff;
  text-align: center;
  display: block;
}

.btns {
  display: flex;
  justify-content: center;
}

.title-msg {
  text-align: center;
  margin-top: 10px;
}
.down-item {
  margin-left: 20px;
  margin-bottom: 15px;
  span {
    width: 80px;
    display: inline-block;
    text-align: right;
  }
  .first {
    width: 240px;
  }
}
</style>
