<template>
  <basic-container>
    <div>
      <el-tabs v-model="activeName" @tab-click="tabClickFn">
        <el-tab-pane label="系统对接" name="first"></el-tab-pane>
        <el-tab-pane label="手动上传" name="second"></el-tab-pane>
      </el-tabs>
      <!-- 系统对接 -->
      <avue-crud
        v-if="activeName === 'first'"
        class="secondTable"
        :data="tableData2"
        :option="option2"
        :page.sync="page"
        :table-loading="tableLoading"
        @on-load="getList2"
        @size-change="sizeChange"
        @search-change="
          (form, done) => {
            return searchVal(form, done, 'duijie');
          }
        "
        @current-change="currentChange"
      >
        <template slot="menuLeft">
          <div>
            <span class="mr50"
              >已分配积分值：{{ deptScorePackageInfo.totalScore }}</span
            ><span
              >已结算积分值：{{ deptScorePackageInfo.totalSettledScore }}</span
            >
            <el-progress
              class="mt5 mb10"
              :text-inside="true"
              :stroke-width="26"
              :percentage="deptScorePackageInfo.settledScoreRate"
            ></el-progress>
          </div>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-finished"
            @click="toPrescriptionUpload(scope.row, scope.index, 'duijie')"
            >处方上传
          </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>
      <!-- 手动上传 -->
      <avue-crud
        v-if="activeName === 'second'"
        :data="tableData"
        :option="option1"
        :page.sync="page"
        :table-loading="tableLoading"
        @on-load="getList"
        @size-change="sizeChange"
        @search-change="
          (form, done) => {
            return searchVal(form, done, 'shoudong');
          }
        "
        @current-change="currentChange"
      >
        <template slot="menuLeft">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click.stop="addData()"
            >新增</el-button
          >
        </template>
        <!-- 全部终止 将积分包状态标记已终止，操作栏只提供一个查看按钮  scorePackageStatus==6 （积分包状态为已终止） -->
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-finished"
            @click="toPrescriptionUpload(scope.row, scope.index, 'shoudong')"
            >处方上传
          </el-button>
          <el-button
            v-show="
              scope.row.yjddsh != null &&
                scope.row.yjddsh > 0 &&
                scope.row.scorePackageStatus !== '6'
            "
            type="text"
            size="small"
            icon="el-icon-tickets"
            @click="receiveApproval(scope.row, scope.index)"
            >接单审批
          </el-button>
          <el-button
            v-show="
              (scope.row.settleFlag == null || scope.row.settleFlag == '0') &&
                scope.row.enableType == 0 &&
                (scope.row.shtg == 0 || scope.row.shtg == null) &&
                scope.row.scorePackageStatus !== '6'
            "
            type="text"
            size="small"
            icon="el-icon-tickets"
            @click="stopFn(scope.row, scope.index)"
            >终止
          </el-button>
          <el-button
            v-show="
              (scope.row.scorePackageStatus == null ||
                scope.row.scorePackageStatus <= 2) &&
                scope.row.scorePackageStatus !== '6'
            "
            type="text"
            size="small"
            icon="el-icon-tickets"
            @click="updateSettle(scope.row, scope.index)"
            >编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="toView(scope.row, scope.index)"
            >查看
          </el-button>
          <el-button
            v-show="
              (scope.row.settleFlag == null || scope.row.settleFlag == '0') &&
                scope.row.packageFinishStatus == '1' &&
                scope.row.typeid == '4' &&
                scope.row.scorePackageStatus !== '6'
            "
            type="text"
            size="small"
            icon="el-icon-finished"
            @click="settleById(scope.row)"
            >结算
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-folder-checked"
            @click="exportBtn(scope.row, scope.index)"
            v-if="scope.row.scorePackageStatus !== '6'"
            >导出
          </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
          >
        </span>
        <span slot="footer" class="dialog-footer">
          注意： 1.报告汇总为封面+任务数据汇总+任务列表明细。<br />

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

      <!-- 添加的弹窗 -->
      <el-dialog
        :title="showTit"
        :visible.sync="addDialog"
        v-if="addDialog"
        width="60%"
        :before-close="handleClose"
        center
      >
        <el-form
          :model="addForm"
          :rules="rules"
          ref="addForm"
          label-width="120px"
          class="demo-ruleForm"
          :disabled="showTit === '查看'"
        >
          <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="请选择"
                >
                  <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">
              <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="任务个数" 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="subjectLocation">
                <el-select
                  v-model="addForm.subjectLocation"
                  style="width: 100%"
                >
                  <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="packageUserScope">
                <el-select
                  v-model="addForm.packageUserScope"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in packageUserScopeList"
                    :value="item.value"
                    :label="item.label"
                    :key="index"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="积分包编号" prop="packageNum">
                <el-input v-model="packageNum" 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="handleClose">关 闭</el-button>
          <el-button
            v-if="showTit !== '查看'"
            type="primary"
            :loading="buttonLoading"
            @click="sureBtn('addForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- 结算 -->
      <el-dialog
        title="结算"
        :close-on-click-modal="false"
        @close="hideDialog"
        :visible.sync="settleTableVisible"
        center
      >
        <el-form
          ref="settleForm"
          :model="settleForm"
          :rules="settleRules"
          label-width="120px"
          :inline="true"
        >
          <div class="separator">积分包基本信息</div>
          <el-form-item
            label="积分包名称"
            prop="scorePackageName"
            class="settle-label"
          >
            <el-input
              v-model="settleForm.scorePackageName"
              :disabled="true"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="积分包值" prop="userScore" class="settle-label">
            <el-input
              v-model="settleForm.userScore"
              :disabled="true"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="已完成积分值"
            prop="finishScore"
            class="settle-label"
          >
            <el-input
              v-model="settleForm.finishScore"
              :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="settleForm.description"
            ></el-input>
          </el-form-item>

          <div class="separator">结算信息</div>
          <el-form-item
            label="结算渠道"
            prop="subjectLocation"
            class="settle-label"
          >
            <el-select
              v-model="settleForm.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
              v-model="settleForm.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="actualAmount"
            label="实际支付金额"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-if="
                  settleButtonShow &&
                    (scope.row.settleNoteStatus === 0 ||
                      scope.row.settleNoteStatus === 2)
                "
                v-model="scope.row.actualAmount"
                placeholder="请输入实际支付金额"
                @change="actualAmountChange(scope.row)"
                @input="actualAmountInput(scope.row)"
              ></el-input>
              <span v-else>{{ scope.row.actualAmount }}</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="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"
                    v-show="
                      currentRow.yjd != '0' &&
                        currentRow.packageFinishStatus != '1'
                    "
                    >剩余收回</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>
    </div>
  </basic-container>
</template>

<script>
import {
  tableOptions1,
  tableOptions2
} from "@/const/crud/specialTask/patientEdu/index";
import { getDictType } from "@/api/common";
import {
  getDeptScorePackageInfo,
  exportHCPReport
} from "@/api/specialTask/patientEdu";
import {
  getScorePackagePage,
  addWmScorePackage,
  packageUserScope,
  updateEnable,
  updateWmScorePackage,
  searchById,
  saveById
} from "@/api/assignPoints/currency/index";

import { getPackageSn } from "@/api/assignPoints/quota";
import {
  settleById,
  settleSave,
  settleSubmit,
  geSubmitToken
} from "@/api/settle/settle";
import { getSubSelect, getSettleSubSelect } from "@/api/admin/deptSub";
import { invoiceDictMap, subjectTypeMap } from "@/const/constants/invoice";
import { SUBJECT_TYPE_MAP } from "@/const/auth";
import BigNumber from "bignumber.js";

export default {
  name: "patientEdu",
  data() {
    return {
      activeName: "first",
      packageUserScopeList: [],
      enableForm: {},
      enableFlagDig: false,
      enableRule: {
        enableFlag: [
          { required: true, message: "请选择积分回收方式", trigger: "change" }
        ]
      },
      currentId: "",
      subjectTypeList: [], // 结算渠道下拉列表
      deptScorePackageInfo: {}, // 系统对接进度条 信息
      addForm: {
        typeid: "", // 接单对象类型
        subjectLocation: "",
        packageUserScope: "1", // 默认仅内部可见
        taskTypeId: ""
      },
      typeidList: [], // 接单对象类型
      taskTypeList1: [], // 任务类型
      tableLoading: false,
      option1: tableOptions1,
      option2: tableOptions2,
      tableData: [],
      tableData2: [],
      page: {
        pageSize: 20,
        currentPage: 1
      },
      exportDig: false,
      currentRow: {},
      taskExportLoading: 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" }
        ],
        packageUserScope: [
          { required: true, message: "请选择接单对象类型", trigger: "change" }
        ]
      },
      showTit: "",
      settleTableVisible: false,
      buttonLoading: false,
      settleForm: {
        subjectLocation: "",
        packageUserScope: "1",
        scorePackageName: "",
        relationScoreId: "",
        kfpjf: "",
        taskTypeList: [],
        userList: [],
        userScore: ""
      },
      settleRules: {
        invoiceCategory: [
          { required: true, message: "请选择发票类目", trigger: "blur" }
        ],
        subjectLocation: [
          { required: true, message: "请选择结算渠道", trigger: "blur" }
        ]
      },
      settleButtonShow: false,
      gridData: [],
      subList: [],
      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: "信息服务费" }
      ],
      invoiceList2: [{ value: 15, label: "设计服务" }],
      invoiceList3: [],
      searchForm: {},
      packageNum: "",
      userScore: "",
      pointsForm: {},
      submitToken: ""
    };
  },
  watch: {
    activeName: {
      handler: function(newVal) {
        this.page = {
          pageSize: 20,
          currentPage: 1
        };
        if (newVal === "first") {
          this.getList2(this.page);
          this.getDeptScorePackageInfo();
        } else if (newVal === "second") {
          this.getList(this.page);
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.activeName =
      this.$store.getters.patientEduType === "second" ? "second" : "first";
    this.getPackageUserScopeList(); // 接单对象范围
    // this.getSubjectType()
    this.getTypeidList();
    this.getTaskTypeList();
    this.getInvoiceList();
    this.showSubSelect();
    this.getInvoiceDict();
  },
  methods: {
    async getPackageSnFn() {
      const res = await getPackageSn();
      this.packageNum = res.data.data;
    },
    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;
      });
    },
    // activeName切换
    tabClickFn(type) {
      if (type.name === "second") {
        this.$store.commit("ADD_PATIENT_EDU_TYPE", "second");
      } else {
        this.$store.commit("DEL_PATIENT_EDU_TYPE");
      }
    },
    // 系统对接进度条信息
    async getDeptScorePackageInfo() {
      const res = await getDeptScorePackageInfo();
      this.deptScorePackageInfo = res.data.data;
    },
    // 获取-发票类目
    getInvoiceList() {
      getDictType({ type: "invoice_category" }).then(res => {
        this.invoiceList = res.data.data;
      });
    },
    // 获取-任务类型
    getTaskTypeList() {
      getDictType({ type: "task_type_hcp" }).then(res => {
        this.taskTypeList1 = res.data.data;
      });
    },
    // 获取-接单对象类型
    getTypeidList() {
      getDictType({ type: "typeid_hcp" }).then(res => {
        this.typeidList = res.data.data;
      });
    },
    // 获取-结算渠道
    getSubjectType() {
      getDictType({ type: "subject_type" }).then(res => {
        this.subjectTypeList = res.data.data;
      });
    },
    // 接单审批
    receiveApproval(row) {
      this.$router.push({
        path: "/admin/specialTask/patientEdu/approval?id=" + row.id
      });
    },
    // 获取接单对象范围列表
    getPackageUserScopeList() {
      packageUserScope()
        .then(res => {
          this.packageUserScopeList = res.data.data;
          if (!this.packageUserScopeList) {
            return this.$message.error("当前机构未配置接单对象范围");
          }
        })
        .catch(() => {
          this.$message.error("当前机构未配置接单对象范围");
        });
    },
    // 手动上传-获取列表
    getList(page, params) {
      this.tableLoading = true;
      let userIdList = [];
      if (params && params.acceptSug) {
        userIdList.push(params.acceptSug);
      }
      getScorePackagePage(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
            packageType1: "5", // 必传固定值
            packageType2: "2" // 必传固定值
          },
          params,
          { userIdList },
          { sourceType: "0" }
        )
      )
        .then(response => {
          this.tableData = [];
          this.tableData = response.data.data.records;
          // 接单对象取userList
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i]["userList"]) {
              this.tableData[i]["acceptSug"] = this.tableData[i]["userList"][0];
            }
          }
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 系统对接-获取列表
    getList2(page, params) {
      this.tableLoading = true;
      let userIdList = [];
      if (params && params.acceptSug) {
        userIdList.push(params.acceptSug);
      }
      getScorePackagePage(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
            packageType1: "5", // 必传固定值
            packageType2: "2" // 必传固定值
          },
          params,
          { userIdList },
          { sourceType: "1" }
        )
      )
        .then(response => {
          this.tableData2 = [];
          this.tableData2 = response.data.data.records;
          // 接单对象取userList
          for (let i = 0; i < this.tableData2.length; i++) {
            if (this.tableData2[i]["userList"]) {
              this.tableData2[i]["acceptSug"] = this.tableData2[i][
                "userList"
              ][0];
            }
          }
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 新增-展示弹窗
    addData() {
      this.getPackageSnFn();
      this.showTit = "新增";
      this.addDialog = true;
    },
    // 新增-确认按钮
    sureBtn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.addForm.packageType1 = "5";
          this.addForm.packageType2 = "2";
          this.addForm.packageUserScope = "1";
          if (this.showTit === "新增") {
            this.addForm.packageSn = this.packageNum;
            addWmScorePackage(this.addForm)
              .then(response => {
                this.$message.success(response.data.msg);
                this.getList(this.page);
                this.handleClose();
                this.buttonLoading = false;
              })
              .catch(() => {
                this.buttonLoading = false;
              });
          } else {
            // 编辑保存
            saveById(this.addForm)
              .then(response => {
                this.$message.success("编辑成功");
                this.getList(this.page);
                this.handleClose();
                this.buttonLoading = false;
              })
              .catch(() => {
                this.buttonLoading = false;
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 终止
    stopFn(row) {
      this.currentId = row.id;
      this.currentRow = row;
      this.enableFlagDig = true;
    },
    // 终止确认按钮
    enableFlagBtn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let args = {
            enableType: this.enableForm.enableFlag,
            id: this.currentId
          };
          updateEnable(args).then(response => {
            this.$message.success("终止成功");
            this.enableFlagDig = false;
            this.getList(this.page);
            this.enableForm = {};
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 取消按钮
    cancelBtn() {
      this.enableFlagDig = false;
      this.enableForm = {};
    },
    // 编辑
    updateSettle(row) {
      this.showTit = "编辑";
      this.addDialog = true;
      // 回显数据
      let arg = {
        id: row.id
      };
      searchById(arg)
        .then(response => {
          this.addForm = response.data.data;
        })
        .catch(() => {
          console.log("请求异常");
        });
    },
    // 处方上传 type: shoudong/duijie
    toPrescriptionUpload(row, index, type) {
      this.$router.push({
        path: `/admin/specialTask/patientEdu/prescriptionUpload?id=${
          row.id
        }&type=${type}`
      });
    },
    // 导出
    exportBtn(row) {
      this.exportDig = true;
      this.currentRow = row;
    },
    // 导出汇总报告
    taskExport() {
      this.taskExportLoading = true;
      let row = this.currentRow;
      var obj = {
        packageId: row.id
      };
      exportHCPReport(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.settleForm.resetFields();
    },
    // 删除
    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.showTit = "查看";
      this.addDialog = true;
      // 回显数据
      let arg = {
        id: row.id
      };
      searchById(arg)
        .then(response => {
          this.addForm = response.data.data;
        })
        .catch(() => {
          console.log("请求异常");
        });
    },
    // 查询
    searchVal(form, done, type) {
      this.searchForm = form;
      this.page.currentPage = 1;
      if (type === "shoudong") {
        this.getList(this.page, form);
      } else if (type === "duijie") {
        this.getList2(this.page, form);
      }
      done();
    },
    // 分页查询
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    // 关闭弹窗
    handleClose() {
      this.addDialog = false;
      this.showTit = "";
      this.addForm = this.$options.data().addForm;
    },
    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.userScore) * Number(value)).toFixed(2);
      let actualAmount = 0;

      if (
        this.settleForm.serviceCharge !== null &&
        this.settleForm.serviceCharge !== undefined
      ) {
        console.log(
          "this.settleForm.serviceCharge",
          this.settleForm.serviceCharge
        );
        actualAmount = (value / (this.settleForm.serviceCharge + 1)).toFixed(2);
        e.actualAmount = actualAmount;
        this.calcPayAmount();
      }
    },
    // 计算实际支付金额
    calcPayAmount() {
      if (
        this.settleForm.serviceCharge !== null &&
        this.settleForm.serviceCharge !== undefined
      ) {
        this.gridData.forEach((ele, index) => {
          if (ele.settleAmount) {
            const serviceCharge = new BigNumber(
              this.settleForm.serviceCharge + 1
            );
            const amount = serviceCharge.times(ele.settleAmount);
            this.$set(this.gridData[index], "actualAmount", amount.toFixed(2));
          }
        });
      }
    },
    // settleAmountInput(e) {
    //   let value = e
    //   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'); //只能输入两个小数
    //   this.settleForm.settleAmount = value
    // },
    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;
      let actualAmount = 0;
      if (value) {
        discount = (Number(value) / Number(this.userScore)).toFixed(2);
        actualAmount = (value / (this.settleForm.serviceCharge + 1)).toFixed(2);
      }
      console.log("discount", discount);

      e.settleAmount = value;
      e.discount = discount;
      e.actualAmount = actualAmount;
      this.calcPayAmount();
    },
    hideDialog() {
      this.settleTableVisible = false;
      this.settleForm = {};
      this.getList(this.page, this.searchForm);
    },
    // 打开结算弹窗
    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(async response => {
          const res = response.data.data;
          this.gridData = res.notes;
          this.settleForm = res.wsp;
          this.id = res.wsp.id;
          this.scorePackageName = res.wsp.scorePackageName;
          this.settleForm.finishScore = res.finishScore;
          this.userScore = res.wsp.userScore;

          this.subTypeChange(this.settleForm.subjectLocation);
          const tokenResult = await geSubmitToken();
          this.submitToken = tokenResult.data;
          this.settleTableVisible = true;
        })
        .catch(err => {
          console.log("err", err);
          // this.hideDialog();
        });
    },
    async showSubSelect() {
      const res1 = await getSettleSubSelect();
      this.subList = res1.data.data;
      if (!this.subList) return;
      this.pointsForm.subType = this.subList[0].subjectType;
    },
    // 合计计算
    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);
          } else {
            sums[index] = "N/A";
          }
        } else {
          sums[index] = "*";
        }
      });
      return sums;
    },
    discountInput(e) {
      console.log("e", e);
      let value = e.discount + "";
      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.userScore) * 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.userScore) * 1.2;
        let total1 = Number(this.userScore) * 1.2;
        // 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.userScore)).toFixed(2);
        let actualAmount = (
          value /
          (this.settleForm.serviceCharge + 1)
        ).toFixed(2);
        e.settleAmount = value;
        e.discount = discount;
        e.actualAmount = actualAmount;
      } else {
        e.settleAmount = 0;
        e.discount = 0;
        e.actualAmount = 0;
      }
      this.calcPayAmount();
    },
    actualAmountChange(e) {
      let value = e.actualAmount;
      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 settleAmount = 0;
      let discount = 0;
      if (
        this.settleForm.serviceCharge !== undefined &&
        this.settleForm.serviceCharge !== null
      ) {
        settleAmount = (value / (1 + this.settleForm.serviceCharge)).toFixed(2);
        discount = (settleAmount / Number(this.userScore)).toFixed(2);
        console.log(settleAmount);
      } else {
        console.log("未选择结算渠道");
      }
      e.actualAmount = value;
      e.settleAmount = settleAmount;
      e.discount = discount;
    },
    actualAmountInput(e) {
      let value = e.actualAmount;
      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 settleAmount = 0;
      let discount = 0;
      if (
        this.settleForm.serviceCharge !== undefined &&
        this.settleForm.serviceCharge !== null
      ) {
        settleAmount = (value / (1 + this.settleForm.serviceCharge)).toFixed(2);
        discount = (settleAmount / Number(this.userScore)).toFixed(2);
      } else {
        console.log("未选择结算渠道");
      }
      e.actualAmount = value;
      e.settleAmount = settleAmount;
      e.discount = discount;
    },
    settleSave() {
      if (!this.id) {
        this.$message.error("数据异常");
        return;
      }
      this.$refs["settleForm"].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;
            }
          }
          this.buttonLoading = true;
          const args = {
            id: this.id,
            invoiceCategory: this.settleForm.invoiceCategory,
            description: this.settleForm.description,
            subjectLocation: this.settleForm.subjectLocation,
            notes: this.gridData
          };
          settleSave(args)
            .then(response => {
              if (response.data.code === 0) {
                this.$message.success("保存成功");
                //this.$message.success("提交结算申请结算成功");
              }
              this.hideDialog();
              this.buttonLoading = false;
            })
            .catch(() => {
              this.buttonLoading = false;
              // this.hideDialog();
            });
        }
      });
    },
    settleSubmit() {
      if (!this.id) {
        this.$message.error("数据异常");
        return;
      }
      this.$refs["settleForm"].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;
            }
          }
          this.buttonLoading = true;
          const args = {
            id: this.id,
            invoiceCategory: this.settleForm.invoiceCategory,
            description: this.settleForm.description,
            subjectLocation: this.settleForm.subjectLocation,
            notes: this.gridData,
            token: this.submitToken
          };
          settleSubmit(args)
            .then(response => {
              if (response.data.code === 0) {
                this.$message.success("提交成功");
              }
              this.hideDialog();
              this.buttonLoading = false;
            })
            .catch(() => {
              this.buttonLoading = false;
              // this.hideDialog();
            });
        }
      });
    },
    subTypeChange(val) {
      if (!val) return;
      this.invoiceList = [];
      delete this.settleForm.invoiceCategory;
      const selectedSubType = this.subList.filter(
        ele => ele.subjectLocation === val
      );

      // 费率
      this.settleForm.serviceCharge =
        (selectedSubType[0].serviceCharge || 0) / 100;
      this.calcPayAmount();

      this.invoiceList = this[SUBJECT_TYPE_MAP[val] + "_invoice_dict"].filter(
        ele => {
          if (
            selectedSubType[0].subjectInvoiceCategory &&
            selectedSubType[0].subjectInvoiceCategory
              .split(",")
              .includes(ele.value)
          ) {
            return ele;
          }
        }
      );
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.secondTable {
  ::v-deep.avue-crud__menu .avue-crud__left {
    width: calc(100% - 120px - 50px);
  }
}

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

.settle-desc {
  width: 80%;

  ::v-deep textarea {
    width: 600px;
  }
}
</style>
