<style scoped>
::v-deep .margin-small .ant-row {
  margin-bottom: 0;
}

::v-deep .ant-steps-dot .ant-steps-item-content {
  width: auto;
}

::v-deep
  .ant-steps-dot
  .ant-steps-item-active
  .ant-steps-item-icon
  > .ant-steps-icon
  .ant-steps-icon-dot {
  background: rgb(11, 190, 135);
  width: 15px;
  height: 15px;
  /* margin-top: 5px; */
  margin-left: 2px;
}

::v-deep .endStatus .ant-steps-item-icon > .ant-steps-icon .ant-steps-icon-dot {
  background: #1890ff !important;
  width: 15px;
  height: 15px;
  /* margin-top: 5px; */
  /* margin-left: 2px; */
}

::v-deep .ant-steps-dot .ant-steps-item-icon {
  width: 15px;
  height: 15px;
  margin-top: 5px;
  margin-left: -4px;
}
</style>
<template>
  <div class="policy-management-content">
    <div class="control-con-title">
      <div>
        <span class="policy-export-btn">充值列表</span>
      </div>
      <div>
        <!-- <span class="add-acount-policy-btn">
                          <a-button>快递信息</a-button>
                        </span> -->
        <span class="add-acount-policy-btn">
          <a-button @click="handleAddPleace" type="primary">充值申请</a-button>
        </span>
      </div>
    </div>
    <div class="control-con-header">
      <a-form class="grid-form" layout="inline" :form="searchForm" hide-required-mark>
        <a-row class="grid-form-options">
          <a-form-item class="grid-form-item" label="客户名称：" :colon="false">
            <!-- <a-input v-model="configForm.companyName" placeholder="请输入公司名称" allow-clear/> -->
            <a-input
              v-model="configForm.advertiserName"
              placeholder="请输入客户名称"
              allow-clear
            />
          </a-form-item>
          <a-form-item class="grid-form-item" label="产品名称：" :colon="false">
            <a-input
              v-model="configForm.productName"
              placeholder="请输入产品名称"
              allow-clear
            />
          </a-form-item>
          <a-form-item class="grid-form-item" label="媒体：" :colon="false">
            <a-select
              v-model="configForm.paymentMedia"
              style="width: 200px; margin-left: 10px"
              :filterOption="filterOption"
              showSearch
              allowClear
              placeholder="请选择媒体"
            >
              <a-select-option value="1"> 头条</a-select-option>
              <a-select-option value="2"> 快手</a-select-option>
              <a-select-option value="9"> 广点通</a-select-option>
              <a-select-option value="7"> 磁力金牛</a-select-option>
              <a-select-option value="11"> 头条&快手</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item class="grid-form-item" label="状态：" :colon="false">
            <a-select
              v-model="configForm.auditStatus"
              style="width: 200px; margin-left: 10px"
              :filterOption="filterOption"
              showSearch
              allowClear
              placeholder="请选择状态"
            >
              <a-select-option value="1">待审核</a-select-option>
              <a-select-option value="2">待充值</a-select-option>
              <a-select-option value="3">充值完成</a-select-option>
              <a-select-option value="4">临时充值</a-select-option>
              <a-select-option value="5">审核拒绝</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item class="grid-form-item" label="返点类型：" :colon="false">
            <a-select
              v-model="configForm.rebateType"
              style="width: 200px; margin-left: 10px"
              :filterOption="filterOption"
              showSearch
              allowClear
              placeholder="请选择返点类别"
            >
              <a-select-option value="1"> 返货</a-select-option>
              <a-select-option value="2"> 返现</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item class="grid-form-item" label="账户ID：" :colon="false">
            <a-input
              v-model="configForm.accountId"
              placeholder="请输入账户ID"
              allow-clear
            />
          </a-form-item>
          <a-form-item class="grid-form-item" label="是否后补：" :colon="false">
            <a-select
              v-model="configForm.amends"
              style="width: 200px; margin-left: 10px"
              :filterOption="filterOption"
              showSearch
              allowClear
              placeholder="请选择是否后补"
            >
              <a-select-option value="1">是</a-select-option>
              <a-select-option value="2">否</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item class="grid-form-item" label="申请时间：" :colon="false">
            <a-range-picker
              v-model="configForm.time"
              format="YYYY-MM-DD"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item class="form-handle-btn">
            <a-button type="default" class="reset-class" @click="handleResetList"
              >重置
            </a-button>
            <a-button type="primary" @click="handleQueryList">搜索</a-button>
            <a-button @click="exportData" :loading="exportLoading">导出</a-button>
          </a-form-item>
        </a-row>
      </a-form>
    </div>
    <div class="control-con-table">
      <a-table
        ref="table"
        size="middle"
        bordered
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="controlLoading"
        :scroll="{ x: 1000 }"
      >
        <span slot="auditStatus" slot-scope="text, record">
          <a @click="showLog(record)">{{ text | auditRechargeName }}</a>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleLook(record)">查看</a>
          <a-divider
            type="vertical"
            v-if="record.applicanterId == userInfo().id && record.auditStatus == '5'"
          />
          <!-- record.status == '1' ||  -->
          <a
            @click="handleDetail(record, 'edit')"
            v-if="record.applicanterId == userInfo().id && record.auditStatus == '5'"
            >编辑</a
          ><a-divider type="vertical" v-if="record.auditStatus == '4'" />
          <!-- record.status == '1' ||  -->
          <a
            @click="handleLook(record, 'upload')"
            v-if="record.auditStatus == '4' && roleCode == 'meidaManager'"
            >附件上传</a
          ><a-divider type="vertical" v-if="record.auditStatus == '2'" />
          <!-- record.status == '1' ||  -->
          <a @click="handleCopy(record)" v-if="record.auditStatus == '2'">复制</a>

          <a-divider type="vertical" v-if="record.auditStatus == '3'" />
          <!-- record.status == '1' ||  -->
          <a
            @click="
              editFileVisible = true;
              editFilesData = [];
              editFilesId = record.id;
            "
            v-if="
              record.auditStatus == '3' &&
              (roleCode == 'meidaManager' || roleCode == 'admin')
            "
            >修改附件</a
          >
          <a-divider
            type="vertical"
            v-if="
              (record.auditStatus == '1' || record.auditStatus == '2') &&
              userInfo().id == record.applicanterId
            "
          />
          <!-- record.status == '1' ||  -->

          <a-popconfirm title="确定撤销此记录吗?" @confirm="() => remove(record.id)">
            <a
              v-if="
                (record.auditStatus == '1' || record.auditStatus == '2') &&
                userInfo().id == record.applicanterId
              "
              >撤销</a
            >
          </a-popconfirm>
        </span>
      </a-table>
      <a-pagination
        class="pagin-table-class"
        :total="totalAll"
        :show-total="(total) => `共 ${totalAll} 条`"
        size="small"
        show-size-changer
        show-quick-jumper
        v-model="tablePag.page"
        @change="handleOnShowSizeChange"
        @showSizeChange="handleOnShowSizeChange"
      />
    </div>

    <!-- 充值申请 -->
    <a-modal
      v-if="auditPolicyStatus"
      title="充值申请"
      :visible="auditPolicyStatus"
      :footer="null"
      v-dialog-drag
      :width="650"
      @cancel="
        auditPolicyStatus = false;
        queryByIdList = { accountList: [] };
        totalAmount = undefined;
        rebateData = undefined;
      "
    >
      <a-form-model
        ref="queryByIdList"
        :model="queryByIdList"
        :rules="policyOperationRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="客户名称" prop="advertiserId">
          <a-select
            v-model="queryByIdList.advertiserId"
            placeholder="请选择客户名称"
            showSearch
            optionFilterProp="children"
            :filterOption="filterOption"
            allow-clear
            @change="getNewProductList"
          >
            <a-select-option
              :value="item.id"
              v-for="(item, index) of advertiserList"
              :key="index"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="产品名称" prop="productId">
          <a-select
            v-model="queryByIdList.productId"
            placeholder="请选择产品名称"
            showSearch
            optionFilterProp="children"
            :filterOption="filterOption"
            allow-clear
            @change="getMediaList"
          >
            <a-select-option
              :value="item.id"
              v-for="(item, index) of productNewList"
              :key="index"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="媒体" prop="paymentMedia">
          <a-select
            v-model="queryByIdList.paymentMedia"
            placeholder="请选择媒体"
            showSearch
            optionFilterProp="children"
            :filterOption="filterOption"
            allow-clear
            @change="getProjectList"
          >
            <a-select-option
              :value="item.name"
              v-for="(item, index) of mediaList"
              :key="index"
            >
              {{ item.name | paymentMediaName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="选择端口" prop="paymentPort">
          <a-select
            v-model="queryByIdList.paymentPort"
            placeholder="请选择端口"
            showSearch
            optionFilterProp="children"
            :filterOption="filterOption"
            allow-clear
            @change="getMoney"
          >
            <a-select-option
              :value="item.paymentPort"
              v-for="(item, index) of paymentPortList"
              :key="index"
            >
              {{ item.portName }}
            </a-select-option>
          </a-select>
          <p v-if="rebateData" style="margin-bottom: 0">
            返点类型：{{
              rebateData.rebateType == 1 ? "返货" : "返现"
            }}
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 返点比例：{{
              rebateData.rebateRate
            }}%
          </p>
        </a-form-model-item>

        <a-form-model-item label="可用金额" prop="totalAmount">
          {{ totalAmount ? allMoney(totalAmount) : "-" }}
        </a-form-model-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="是否后补"
          prop="amends"
        >
          <a-radio-group v-model="amends">
            <a-radio-button value="2">否</a-radio-button>
            <a-radio-button value="1">是</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-model-item label="备注" prop="remarks">
          <a-textarea
            v-model="queryByIdList.remarks"
            placeholder="请输入备注"
            allow-clear
            @change="handleRemarksChange"
          />
        </a-form-model-item>

        <a-form-model-item label="类型" prop="rechargeType">
          <a-select
            v-model="queryByIdList.rechargeType"
            placeholder="请选择类型"
            allow-clear
          >
            <a-select-option :value="1">自运营充值</a-select-option>
            <a-select-option :value="2">客运营充值</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="项目" prop="projectId">
          <!--                    :rules="[-->
          <!--                    {-->
          <!--                    required: queryByIdList.rechargeType == 1,-->
          <!--                    message: '请选择项目',-->
          <!--                    trigger: 'change',-->
          <!--                    },-->
          <!--                    ]"-->

          <a-select
            v-model="queryByIdList.projectId"
            placeholder="请选择项目"
            showSearch
            optionFilterProp="children"
            :filterOption="filterOption"
            allow-clear
            @change="getAccountList"
          >
            <a-select-option
              :value="item.id"
              v-for="(item, index) of projectList"
              :key="index"
            >
              {{ item.name }}（{{ item.media }})
            </a-select-option>
          </a-select>
          <a @click="addAccount">添加账户</a>
        </a-form-model-item>
        <div
          v-for="(item, index) in queryByIdList.accountList"
          style="position: relative"
        >
          <a-form-model-item
            label="选择账户"
            :prop="'accountList.' + index + '.accountId'"
            :rules="[{ required: true, message: '请选择账户', trigger: 'change' }]"
            v-if="queryByIdList.rechargeType == 1"
          >
            <a-select
              v-model="item.accountId"
              placeholder="请选择账户"
              showSearch
              optionFilterProp="children"
              :filterOption="filterOption"
              allow-clear
              @change="getAccountInfo($event, item)"
            >
              <a-select-option
                :value="item.id"
                v-for="(item, index) of accountList"
                :key="index"
                :disabled="
                  queryByIdList.accountList.findIndex((c) => {
                    return c.accountId == item.id;
                  }) > -1
                "
              >
                {{ item.id }}({{ item.name }})
              </a-select-option>
            </a-select>
            <p v-if="!!item.accountMoney">账户余额：{{ allMoney(item.accountMoney) }}</p>
          </a-form-model-item>
          <a-form-model-item
            label="账户"
            :prop="'accountList.' + index + '.accountId'"
            :rules="[{ required: true, message: '请填写账户', trigger: 'blur' }]"
            v-else-if="queryByIdList.rechargeType == 2"
          >
            <a-input placeholder="请输入账户" v-model.number="item.accountId"></a-input>
          </a-form-model-item>
          <a-form-model-item
            label="到账金额"
            prop="receivedAmount"
            :prop="'accountList.' + index + '.receivedAmount'"
            :rules="[{ required: true, message: '请输入到账金额', trigger: 'blur' }]"
          >
            <a-input-number
              v-model="item.receivedAmount"
              :step="0.01"
              :precision="2"
              :min="0"
              @change="editMoneyNew($event, 1, index)"
            />
          </a-form-model-item>
          <a-form-model-item
            label="现金金额"
            prop="cashAmount"
            :prop="'accountList.' + index + '.cashAmount'"
            :rules="[{ required: true, message: '请输入现金金额', trigger: 'blur' }]"
          >
            <a-input-number
              v-model="item.cashAmount"
              :step="0.01"
              :precision="2"
              :min="0"
              @change="editMoneyNew($event, 2, index)"
            />
          </a-form-model-item>
          <a
            v-if="index > 0"
            style="position: absolute; right: 0; top: 0; z-index: 10"
            @click="removeAccount(index)"
            >删除</a
          >
        </div>
      </a-form-model>
      <div solt="footer" style="display: flex; justify-content: end">
        <div>
          <a-button
            type="primary"
            class="cancel-btn"
            @click="handleAuditSure"
            :loading="confirmLoading"
            style="margin: 0 10px"
            >确定
          </a-button>
        </div>
        <div>
          <a-button type="default" class="cancel-btn" @click="handleAuditCancel"
            >取消
          </a-button>
        </div>
      </div>
    </a-modal>
    <!-- 操作记录 -->
    <a-modal
      v-if="logVisible"
      title="操作记录"
      :visible="logVisible"
      @cancel="logVisible = false"
      :footer="null"
      v-dialog-drag
    >
      <div style="height: 400px; overflow: auto; padding: 15px">
        <a-steps
          progress-dot
          direction="vertical"
          v-model="logActive"
          style="width: 100%"
          disbaled
        >
          <a-step
            :title="`${item.roleName}(${item.userName})${
              item.auditStatus == '0'
                ? '创建申请'
                : item.auditStatus == -1
                ? '退回修改'
                : item.auditStatus == '3'
                ? '充值完成'
                : item.auditStatus == '4'
                ? '临时充值'
                : item.auditStatus == '5'
                ? '审核拒绝'
                : item.auditStatus == '6'
                ? '财务审核通过'
                : item.auditStatus == '2'
                ? '待充值'
                : item.auditStatus == '1'
                ? '待审核'
                : '-'
            }`"
            :description="`${item.time}`"
            v-for="(item, index) in logList"
            :key="index"
            disabled
            :class="{ endStatus: item.auditStatus == 3 }"
          />
        </a-steps>
      </div>
    </a-modal>

    <!-- 查看详情 -->
    <a-modal
      v-if="paymentTypeDisable"
      title="审核"
      :visible="paymentTypeDisable"
      :footer="null"
      v-dialog-drag
      :width="650"
      @cancel="
        paymentTypeDisable = false;
        queryByIdList = { accountList: [] };
        files = undefined;
      "
    >
      <a-form-model
        ref="showForm"
        :model="queryByIdList"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        class="margin-small"
      >
        <div v-if="this.queryByIdList.type != 'upload'">
          <a-form-model-item label="客户名称" prop="advertiserName">
            {{ queryByIdList.advertiserName }}
          </a-form-model-item>
          <!--                    <a-form-model-item label="产品名称" prop="productName">-->
          <!--                        {{ queryByIdList.productName }}-->
          <!--                    </a-form-model-item>-->
          <!--                    <a-form-model-item label="项目名称" prop="projectName">-->
          <!--                        {{ queryByIdList.projectName }}-->
          <!--                    </a-form-model-item>-->
          <a-form-model-item label="媒体" prop="paymentMedia">
            {{ queryByIdList.paymentMedia | paymentMediaName }}
          </a-form-model-item>
          <a-form-model-item
            label="端口"
            prop="portName"
            v-if="queryByIdList.paymentMedia != '2'"
          >
            {{ queryByIdList.portName }}
          </a-form-model-item>
          <a-form-model-item label="类型" prop="rechargeType">
            {{
              queryByIdList.rechargeType
                ? queryByIdList.rechargeType == "1"
                  ? "自运营充值"
                  : "客运营充值"
                : "-"
            }}
          </a-form-model-item>
          <a-form-model-item
            label="备注"
            prop="portName"
            v-if="queryByIdList.remarks != '' && queryByIdList.remarks != null"
          >
            {{ queryByIdList.remarks }}
          </a-form-model-item>
          <div
            style="
              max-height: 350px;
              overflow: auto;
              border-top: 3px solid #f2f2f2;
              border-bottom: 3px solid #f2f2f2;
              margin-bottom: 15px;
            "
          >
            <div v-for="(item, index) in queryByIdList.accountList" :key="index">
              <a-form-model-item label="序号" prop="index" style="color: red">
                {{ index + 1 }}
              </a-form-model-item>

              <a-form-model-item
                label="端口"
                prop="agentName"
                v-if="item.agentName != '' && item.agentName != null"
              >
                {{ item.agentName }}
              </a-form-model-item>
              <a-form-model-item label="产品" prop="productName">
                {{ item.productName }}
              </a-form-model-item>

              <a-form-model-item label="账户" prop="accountName">
                {{
                  item.accountName
                    ? item.accountId + "(" + item.accountName + ")"
                    : item.accountId
                }}
              </a-form-model-item>
              <a-form-model-item label="政策" prop="rebateRate">
                返点类型：{{
                  item.rebateType == 1 ? "返货" : "返现"
                }}
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 返点比例：{{
                  item.rebateRate
                }}%
              </a-form-model-item>
              <a-form-model-item label="现金金额" prop="cashAmount">
                {{ item.cashAmount }}
              </a-form-model-item>
              <a-form-model-item label="到账金额" prop="receivedAmount">
                {{ item.receivedAmount }}
              </a-form-model-item>
            </div>
          </div>
        </div>
        <a-form-model-item
          v-if="queryByIdList.auditStatus != 3"
          label="图片上传"
          prop="files"
          :rules="{
            required: false,
            message: '请上传图片',
            trigger: 'change',
          }"
        >
          <uploadFile
            :value.sync="files"
            :multiple="true"
            @overUpload="overUpload"
            :fileCount="10"
            :size="10240"
            uploadType="image"
          />
        </a-form-model-item>

        <a-form-model-item
          label="查看图片"
          prop="files"
          v-if="queryByIdList.auditStatus == 3"
        >
          <!-- <a @click="lookImageClick(queryByIdList.files)">查看图片</a> -->
          <div>
            <img
              :src="item"
              alt=""
              v-for="(item, index) in JSON.parse(queryByIdList.files)"
              :key="index"
              style="width: 100px; height: auto; max-height: 100px"
              @click="lookImageClick(queryByIdList.files)"
            />
          </div>
        </a-form-model-item>
      </a-form-model>

      <a-modal
        v-if="lookImageVisible"
        title="查看图片"
        :visible="lookImageVisible"
        :footer="null"
        @cancel="lookImageVisible = false"
        :width="1200"
      >
        <a-carousel arrows v-if="lookImageData && lookImageData != '-'">
          <div
            v-for="(item, index) in JSON.parse(lookImageData)"
            :key="index"
            class="content"
          >
            <div style="display: flex !important; justify-content: space-around">
              <div
                style="
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  width: 1200px;
                "
              >
                <img :src="item" style="width: 100%; max-height: 720px" />
              </div>
            </div>
          </div>
          <a-icon
            type="left-circle"
            slot="prevArrow"
            slot-scope
            style="left: 10px; z-index: 100; font-size: 30px; color: black"
          />
          <a-icon
            type="right-circle"
            slot="nextArrow"
            slot-scope
            style="right: 10px; z-index: 100; font-size: 30px; color: black"
          />
        </a-carousel>
      </a-modal>

      <div
        solt="footer"
        style="display: flex; justify-content: end"
        v-if="queryByIdList.auditStatus != 3 && queryByIdList.auditStatus != 5"
      >
        <div v-if="queryByIdList.auditStatus == 2 && roleCode == 'meidaManager'">
          <a-button type="primary" @click="toLeader" class="cancel-btn"
            >临时通过审核
          </a-button>
        </div>
        <div>
          <a-button
            type="primary"
            class="cancel-btn"
            @click="handleOk"
            :disabled="roleCode == 'financialReview' ? false : !files"
            v-if="
              queryByIdList.auditStatus == 1
                ? roleCode == 'financialReview'
                  ? true
                  : false
                : queryByIdList.auditStatus == 2 || queryByIdList.auditStatus == 4
                ? roleCode == 'meidaManager'
                  ? true
                  : false
                : false
            "
            style="margin: 0 10px"
            >通过审核
          </a-button>
        </div>
        <div>
          <a-popconfirm
            @confirm="handleNo('2')"
            v-if="
              queryByIdList.auditStatus == 1
                ? roleCode == 'financialReview'
                  ? true
                  : false
                : queryByIdList.auditStatus == 2 || queryByIdList.auditStatus == 4
                ? roleCode == 'meidaManager'
                  ? true
                  : false
                : false
            "
          >
            <div slot="title">
              <div>
                拒绝原因:
                <a-textarea
                  placeholder="请输入原因"
                  v-model="approvalContent"
                  :autosize="{ minRows: 3, maxRows: 10 }"
                />
              </div>
            </div>
            <a-button type="default" class="cancel-btn">审核拒绝</a-button>
          </a-popconfirm>
        </div>
      </div>
    </a-modal>
    <a-modal
      v-if="editFileVisible"
      title="修改附件"
      :visible="editFileVisible"
      :footer="null"
      v-dialog-drag
      :width="650"
      @cancel="
        editFileVisible = false;
        editFilesData = [];
        editFilesId = null;
      "
    >
      <uploadFile
        :value.sync="editFilesData"
        :multiple="true"
        @overUpload="overUpload"
        :fileCount="10"
        :size="10240"
        uploadType="image"
      />
      <div solt="footer" style="display: flex; justify-content: end">
        <div>
          <a-button
            type="primary"
            class="cancel-btn"
            @click="handleEditFiles"
            style="margin: 0 10px"
            :disabled="editFilesData.length == 0"
            :loading="editFileLoading"
            >确定
          </a-button>
        </div>
        <div>
          <a-button
            type="default"
            class="cancel-btn"
            @click="
              editFileVisible = false;
              editFilesData = [];
              editFilesId = null;
            "
            >取消</a-button
          >
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script>
import moment from "moment";
import Vue from "vue";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { getAction, postAction, downFile } from "@/api/manage";
import { mapGetters } from "vuex";
import { urlAcount } from "./policy-management-server.js";
import uploadFile from "@/components/uploadFile.vue";

const fileSuffix = ["xlsx", "xls"];
import JTreeSelect from "@/components/jeecg/JTreeSelect";

function allMoney(num, n) {
  n = n || 2;
  let symbol = ",";
  if (num === null) return num;
  if (typeof num !== "number") throw new TypeError("num参数应该是一个number类型");
  if (n < 0) throw new Error("参数n不应该小于0");
  let hasDot = parseInt(num) != num; //这里检测num是否为小数，true表示小数
  let m = n != undefined && n != null ? n : 1;
  num =
    m == 0 ? num.toFixed(m) + "." : hasDot ? (n ? num.toFixed(n) : num) : num.toFixed(m);
  symbol = symbol || ",";
  num = num.toString().replace(/(\d)(?=(\d{3})+\.)/g, function (match, p1, p2) {
    return p1 + symbol;
  });
  if (n == 0 || (!hasDot && !n)) {
    //如果n为0或者传入的num是整数并且没有指定整数的保留位数，则去掉前面操作中的小数位
    num = num.substring(0, num.indexOf("."));
  }
  return num;
}

export default {
  name: "policy-management",
  data() {
    let handleCharacterLen30 = (rule, value, callback) => {
      this.handleExportRules(value, 1, 30, callback);
    };
    let handleCharacterLen100 = (rule, value, callback) => {
      this.handleDescRules(value, 5, 100, callback);
    };
    return {
      editFileVisible: false,
      editFilesData: [],
      editFilesId: null,
      editFileLoading: false,
      amends: "2",
      roleCode: localStorage.getItem("roleCode"),
      approvalContent: undefined,
      showAction: true,
      list: [],
      productList: [],
      advertiserList: [],
      productNewList: [],
      paymentPortList: [],
      projectList: [],
      mediaList: [],
      accountList: [],
      totalAmount: undefined,
      rebateData: undefined,
      paymentTypeDisable: false,
      writeRebate: false,
      showRebate: false,
      oldData: undefined,
      mode2: ["month", "month"],
      confirmLoading: false,
      controlLoading: false,
      logVisible: false,
      logStatus: 0,
      logActive: 2,
      logList: [],
      allSaleListOption: [],
      dataDimensionList: [],
      creativeMediaOptions: [
        {
          id: "",
          name: "不限",
        },
        {
          id: 1,
          name: "头条",
        },
        {
          id: 2,
          name: "快手",
        },

        {
          id: 7,
          name: "磁力金牛",
        },
        {
          id: 9,
          name: "广点通",
        },
        {
          id: 11,
          name: "头条&快手",
        },
      ],

      searchStatusOptions: [
        {
          id: 1,
          name: "待审核",
        },
        {
          id: 3,
          name: "审核通过",
        },
        {
          id: 4,
          name: "临时通过",
        },
        {
          id: 5,
          name: "审核拒绝",
        },
      ],
      subTitleMsgStatus: false,
      remarksStatus: false,
      changeRules: [
        { required: true, message: "请输入产品名称", trigger: "blur" },
        { validator: handleCharacterLen30, trigger: "blur" },
      ],
      addType: "add",
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
      rejectAuditStatus: false,
      rejectionReasonStatus: false,
      auditPolicyStatus: false,
      policyOperationStatus: false,
      voidOperationStatus: false,
      totalAll: 0,
      policyOperationForm: {},
      voidId: undefined,
      reasonForm: {
        desc: "",
      },
      //   queryByIdListRules:{

      //   },
      policyOperationRules: {
        advertiserId: [{ required: true, message: "请选择客户", trigger: "change" }],
        productId: [{ required: true, message: "请选择产品", trigger: "change" }],
        paymentMedia: [{ required: true, message: "请选择投放媒体", trigger: "change" }],
        paymentType: [{ required: true, message: "请选择类型", trigger: "change" }],
        rebateType: [{ required: true, message: "请选择返点类型", trigger: "change" }],
        rebateRate: [{ required: true, message: "请填写返点比例", trigger: "blur" }],
        displayAmount: [{ required: true, message: "请填写垫款金额", trigger: "blur" }],
        cashAmount: [{ required: true, message: "请填写现金金额", trigger: "blur" }],
        paymentPort: [{ required: true, message: "请选择端口", trigger: "change" }],
        rechargeType: [{ required: true, message: "请选择类型", trigger: "change" }],
        // projectId: [{ required: true, message: "请选择项目", trigger: "change" }],
      },
      queryByIdList: {
        accountList: [],
      },
      dataSource: [],
      okType: 3,
      columns: [
        {
          title: "客户名称",
          align: "center",
          dataIndex: "advertiserName",
          width: 250,
        },
        {
          title: "媒体",
          dataIndex: "paymentMedia",
          align: "center",
          width: 100,
          customRender(t) {
            if (t == "1") {
              return "头条";
            } else if (t == "2") {
              return "快手";
            } else if (t == "7") {
              return "磁力金牛";
            } else if (t == "9") {
              return "广点通";
            }
          },
        },
        {
          title: "端口",
          align: "center",
          dataIndex: "portName",
          width: 100,
        },
        {
          title: "是否后补",
          dataIndex: "amends",
          align: "center",
          width: 100,
          customRender(t) {
            if (t == "1") {
              return "是";
            } else if (t == "2") {
              return "否";
            }
          },
        },

        {
          title: "产品名称",
          align: "center",
          dataIndex: "productName",
          width: 200,
        },
        {
          title: "账户ID",
          align: "center",
          dataIndex: "accountIds",
          width: 200,
        },
        {
          title: "现金金额",
          dataIndex: "cashAmounts",
          align: "center",
          width: 100,
          customRender(t) {
            if (t) {
              return allMoney(t);
            } else {
              return "-";
            }
          },
        },
        {
          title: "账显金额",
          dataIndex: "receivedAmounts",
          align: "center",
          width: 100,
          customRender(t) {
            if (!!t) {
              return allMoney(t);
            } else {
              return "-";
            }
          },
        },
        // {
        //   title: "返点类型",
        //   dataIndex: "rebateType",
        //   align: "center",
        //   width: 100,
        //   customRender(t) {
        //     if (t == "1") {
        //       return "返货";
        //     } else if (t == "2") {
        //       return "返现";
        //     }
        //   },
        // },

        {
          title: "充值备注",
          dataIndex: "remarks",
          align: "center",
          width: 100,
        },
        {
          title: "返点",
          dataIndex: "rebateRate",
          align: "center",
          width: 100,
        },
        {
          title: "申请人",
          dataIndex: "applicanter",
          align: "center",
          width: 100,
        },

        {
          title: "申请时间",
          dataIndex: "createTime",
          align: "center",
          scopedSlots: { customRender: "createTime" },
          width: 100,
        },
        {
          title: "状态",
          dataIndex: "auditStatus",
          align: "center",
          scopedSlots: { customRender: "auditStatus" },
          width: 100,
        },
        {
          title: "拒绝原因",
          align: "center",
          dataIndex: "approvalContent",
          customRender(t) {
            if (!!t) {
              return t;
            } else {
              return "-";
            }
          },
          width: 150,
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          width: 250,
          fixed: "right",
          scopedSlots: { customRender: "action" },
        },
      ],
      configForm: {
        advertiserName: undefined,
        productName: undefined,
        paymentMedia: undefined,
        time: [],
        rebateType: undefined,
        auditStatus: undefined,
      },
      tablePag: {
        page: 1,
        size: 10,
      },
      addAreaList: [],
      saleShowOption: [],
      addSubjectList: [],
      rejectionReasonList: {},
      tableOnlyId: "",
      saleVisible: false,
      saleInfoList: [],
      salePersonList: [],
      saleLoading: false,
      toLeaderVisible: false,
      exportLoading: false,
      lookImageVisible: false,
      lookImageData: null,
      searchForm: this.$form.createForm(this),
      loadDisabled: false,
      files: undefined,
    };
  },
  components: {
    JTreeSelect,
    uploadFile,
  },
  created() {
    if (localStorage.getItem("applicationLog")) {
      this.configForm.advertiserName = localStorage.getItem("applicationLog");
      localStorage.removeItem("applicationLog");
    }
  },
  mounted() {
    this.handleInitTable();
    // this.handleGetAllSaleList();
    // this.handleAddGetArea();
  },
  methods: {
    exportData() {
      this.exportLoading = true;
      const paramsData = {
        userId: this.userInfo().id,
        advertiserName: this.configForm.advertiserName,
        productName: this.configForm.productName,
        paymentMedia: this.configForm.paymentMedia,
        rebateType: this.configForm.rebateType,
        auditStatus: this.configForm.auditStatus,
        accountId: this.configForm.accountId,
        amends: this.configForm.amends,
        startDate:
          this.configForm.time && this.configForm.time.length == 2
            ? moment(this.configForm.time[0]).format("YYYY-MM-DD")
            : null,
        endDate:
          this.configForm.time && this.configForm.time.length == 2
            ? moment(this.configForm.time[1]).format("YYYY-MM-DD")
            : null,
      };
      downFile(
        urlAcount + "/jeecg-boot/financePayment/rechargeApplication/excelInfo",
        paramsData
      ).then((res) => {
        // console.log(res)
        this.exportLoading = false;
        let blob = new Blob([res], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        // console.log(blob)
        let downloadElement = document.createElement("a");
        let href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = "充值列表" + ".xlsx"; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      });
    },

    lookImageClick(item) {
      this.lookImageVisible = true;
      this.lookImageData = item;
    },

    ...mapGetters(["userInfo"]),
    moment,

    getNewAdvertiserList() {
      var params = {
        table: "finance_payment_pool,advertiser_id,advertiser_name",
        groupBy: "advertiser_id",
      };
      this.postDataAction("/financePayment/pool/querySheetIdAndNameList", params)
        .then((res) => {
          if (res.success) {
            this.advertiserList = res.result;
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {});
    },
    getNewProductList(value) {
      this.$set(this.queryByIdList, "productId", undefined);
      this.$set(this.queryByIdList, "paymentMedia", undefined);
      this.$set(this.queryByIdList, "projectId", undefined);
      this.$set(this.queryByIdList, "paymentPort", undefined);
      this.queryByIdList.accountList = [];
      this.rebateData = undefined;
      this.totalAmount = undefined;

      if (!!value) {
        var params = {
          table: "finance_payment_pool,product_id,product_name",
          groupBy: "product_id",
          paramters: [
            {
              paramter: "advertiser_id",
              value: value,
            },
          ],
        };
        this.postDataAction("/financePayment/pool/querySheetIdAndNameList", params)
          .then((res) => {
            if (res.success) {
              this.productNewList = res.result;
            } else {
              this.$message.warning(res.message);
            }
          })
          .finally(() => {});
      }
    },
    getMediaList(value) {
      this.$set(this.queryByIdList, "paymentMedia", undefined);
      this.$set(this.queryByIdList, "projectId", undefined);
      this.$set(this.queryByIdList, "paymentPort", undefined);
      this.queryByIdList.accountList = [];
      this.rebateData = undefined;
      this.totalAmount = undefined;
      var params = {
        table: "finance_payment_pool,product_id,payment_media",
        groupBy: "payment_media",
        paramters: [
          {
            paramter: "advertiser_id",
            value: this.queryByIdList.advertiserId,
          },
          {
            paramter: "product_id",
            value: value,
          },
        ],
      };
      this.postDataAction("/financePayment/pool/querySheetIdAndNameList", params)
        .then((res) => {
          if (res.success) {
            this.mediaList = res.result;
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {});
    },

    getPaymentPortList(params) {
      this.getAction("/financePayment/pool/queryPaymentPort", params)
        .then((res) => {
          if (res.success) {
            this.paymentPortList = res.result;
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {});
    },

    getProjectList(value) {
      this.$set(this.queryByIdList, "projectId", undefined);
      this.$set(this.queryByIdList, "paymentPort", undefined);
      this.queryByIdList.accountList = [];
      this.rebateData = undefined;
      this.totalAmount = undefined;
      if (!!value) {
        var params = {
          advertiserId: this.queryByIdList.advertiserId,
          type: this.queryByIdList.paymentMedia,
          productId: this.queryByIdList.productId,
          paymentPort: this.queryByIdList.paymentPort,
          paymentMedia: this.queryByIdList.paymentMedia,
        };
        this.getAccountList();
        this.getPaymentPortList(params);
        this.getAction("/financePayment/pool/queryPoolProjectList", params)
          .then((res) => {
            if (res.success) {
              this.projectList = res.result;
            } else {
              this.$message.warning(res.message);
            }
          })
          .finally(() => {});
      } else {
      }
    },
    getMoney() {
      var params = {
        advertiserId: this.queryByIdList.advertiserId,
        type: this.queryByIdList.paymentMedia,
        productId: this.queryByIdList.productId,
        paymentPort: this.queryByIdList.paymentPort,
      };
      this.getAction("/financePayment/pool/queryPool", params)
        .then((res) => {
          if (res.success) {
            this.totalAmount = res.result ? res.result.cashAmount : 0;
            this.rebateData = res.result;
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {});
    },
    getAccountList() {
      this.queryByIdList.accountList = [];
      var params = {
        advertiserId: this.queryByIdList.advertiserId,
        type: this.queryByIdList.paymentMedia,
        projectId: this.queryByIdList.projectId,
      };
      this.getAction("/financePayment/pool/queryPoolAccountList", params)
        .then((res) => {
          if (res.success) {
            this.accountList = res.result;
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {});
    },
    removeAccount(index) {
      this.queryByIdList.accountList.splice(index, 1);
    },
    addAccount() {
      this.queryByIdList.accountList.push({
        accountId: undefined,
        cashAmount: undefined,
        receivedAmount: undefined,
        rebateType: undefined,
        rebateRate: undefined,
        accountMoney: undefined,
      });
    },
    getAccountInfo(value, item) {
      if (!!value) {
        var params = {
          media: this.queryByIdList.paymentMedia,
          accountId: value,
        };
        this.getAction("/financePayment/pool/queryAccountBalance", params)
          .then((res) => {
            if (res.success) {
              item.accountMoney = res.result;
            } else {
              this.$message.warning(res.message);
            }
          })
          .finally(() => {});
      } else {
      }
    },
    handleAddPleace() {
      this.rebateData = undefined;
      this.totalAmount = undefined;
      this.auditPolicyStatus = true;
      this.addType = "add";
      this.getNewAdvertiserList();
    },

    handleFilterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    handleAddTimesChange(date, dateString) {
      this.policyOperationForm.addTimes = dateString;
    },
    showAreaInfo(data) {
      if (data) {
        var dataShow = this.saleShowOption.filter((item) => {
          return item.saleId == data;
        });
        this.policyOperationForm.areaInfo = dataShow[0].nickName;
      } else {
        this.policyOperationForm.areaInfo = undefined;
      }
    },
    handleAddGetArea(data) {
      const paramsData = {
        userId: this.userInfo().id,
      };
      getAction(urlAcount + "/finance/cwjsPolicyInfo/queryAeraByUserId", paramsData)
        .then((result) => {
          if (result.code === 0) {
            const defaultList = result.result[0].UserCompany;
            this.saleShowOption = defaultList.map((item) => {
              return {
                saleId: item.userId,
                saleName: item.userName,
              };
            });
            this.addAreaList = defaultList[0].nickName.split(",");
            this.addSubjectList = result.result[0].companySubjects;
            getAction(
              urlAcount + "/finance/cwjsSaleAssistantInfo/getCwSaleAndAssistantList",
              paramsData
            )
              .then((result) => {
                if (result.code === 0) {
                  for (let i = 0; i < result.result.length; i++) {
                    if (this.saleShowOption[0].saleId == result.result[i].saleId) {
                    } else {
                      this.saleShowOption.push(result.result[i]);
                    }
                  }
                } else {
                  this.$message.error(result.message);
                }
              })
              .catch((error) => {
                console.log(error, "eeee");
              });
          } else {
            this.$message.error(result.message);
          }
        })
        .catch((error) => {
          console.log(error, "eeee");
        });
    },
    handleExamineAll(data) {
      // const paramsData = {
      //   id: data.id,
      //   type: data.type,
      //   userId: this.userInfo().id,
      //   approvalContent: data.value,
      // };
      this.postDataAction("/financePayment/rechargeApplication/updateStatus", data)
        .then((result) => {
          if (result.code === 200) {
            this.rejectAuditStatus = false;
            this.auditPolicyStatus = false;
            this.paymentTypeDisable = false;
            this.handleInitTable();
            this.$message.success(result.message);
          } else {
            this.$message.error(result.message);
          }
        })
        .catch((error) => {
          console.log(error, "eeee");
        });
    },
    // 获取所有的媒体 枚举值
    handleGetAllSaleList() {
      const paramsData = {
        userId: this.userInfo().id,
      };
      getAction(
        urlAcount + "/finance/cwjsSaleAssistantInfo/getSaleListByUserDepart",
        paramsData
      )
        .then((result) => {
          if (result.success) {
            this.allSaleListOption = result.result || [];
          } else {
            this.$message.error(result.message);
          }
        })
        .catch((error) => {
          console.log(error, "eeee");
        });
    },
    showLog(item) {
      this.logVisible = true;
      getAction("/financePayment/rechargeApplication/queryAuditProcess", { id: item.id })
        .then((result) => {
          if (result.code === 200) {
            this.logList = result.result;
            this.logActive = this.logList.length - 1;
          } else {
            this.$message.error(result.message);
          }
        })
        .catch((error) => {
          console.log(error, "eeee");
        })
        .finally(() => {});
    },
    // 获取默认的列表数据
    handleInitTable() {
      this.controlLoading = true;
      const paramsData = {
        userId: this.userInfo().id,
        advertiserName: this.configForm.advertiserName,
        productName: this.configForm.productName,
        paymentMedia: this.configForm.paymentMedia,
        rebateType: this.configForm.rebateType,
        auditStatus: this.configForm.auditStatus,
        accountId: this.configForm.accountId,
        amends: this.configForm.amends,
        startDate:
          this.configForm.time && this.configForm.time.length == 2
            ? moment(this.configForm.time[0]).format("YYYY-MM-DD")
            : null,
        endDate:
          this.configForm.time && this.configForm.time.length == 2
            ? moment(this.configForm.time[1]).format("YYYY-MM-DD")
            : null,
        pageNo: this.tablePag.page,
        pageSize: this.tablePag.size,
      };
      getAction("/financePayment/rechargeApplication/list", paramsData)
        .then((result) => {
          if (result.success == true) {
            let defaultList = result.result.list;
            this.dataSource = defaultList;
            this.totalAll = result.result.total;
          } else {
            this.dataSource = [];
            this.tablePag.page = 1;
            this.totalAll = 0;
            this.$message.error(result.message);
          }
        })
        .catch((error) => {
          console.log(error, "eeee");
        })
        .finally(() => {
          this.controlLoading = false;
        });
    },
    overUpload(urlAll) {
      console.log(urlAll);
    },
    handleRemarksChange(e) {
      const targetVal = e.target.value;
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
      let length = 0;
      let strArr = targetVal.split("");
      strArr.forEach((item) => {
        if (cnReg.test(item)) {
          length += 2;
        } else {
          length += 1;
        }
      });
      if (1 <= length && length <= 500) {
        this.remarksStatus = false;
      } else {
        this.remarksStatus = true;
      }
    },
    handleGroupAbbreviationChange(e) {
      const targetVal = e.target.value;
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
      let length = 0;
      let strArr = targetVal.split("");
      strArr.forEach((item) => {
        if (cnReg.test(item)) {
          length += 2;
        } else {
          length += 1;
        }
      });
      if (1 <= length && length <= 60) {
        this.subTitleMsgStatus = false;
      } else {
        this.subTitleMsgStatus = true;
      }
    },
    disabledDate(current) {
      return current > moment().subtract(1, "day");
    },
    handleAddOrigin() {
      const randomNum = new Date().getTime() + Math.ceil(Math.random() * 1000);
      this.policyOperationForm.defaultFormList.push({
        id: randomNum,
        value: "",
      });
    },
    handleDelOrigin(list) {
      if (this.policyOperationForm.defaultFormList.length === 1) {
        return;
      }
      let formData = this.policyOperationForm.defaultFormList;
      this.policyOperationForm.defaultFormList = formData.filter(
        (item) => list.id !== item.id
      );
    },
    handleIsDianPayChange(e) {
      if (e.target.value === 0) {
        this.policyOperationForm.dianPayCompanyName = "";
        this.policyOperationForm.dianPayCompanyRebateRate = 0;
      }
    },
    handlePrepaidNotChange(e) {
      if (e.target.value === 1) {
        this.policyOperationForm.accountingPeriod = "";
        this.policyOperationForm.dianPayCompanyName = "";
        this.policyOperationForm.dianPayCompanyRebateRate = 0;
        this.policyOperationForm.isDianPay = undefined;
      } else if (e.target.value === 0) {
        this.policyOperationForm.isDianPay = 0;
      }
    },
    handleExportRules(value, min, max, callback) {
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
      let length = 0;
      let strArr = value.split("");
      strArr.forEach((item) => {
        if (cnReg.test(item)) {
          length += 2;
        } else {
          length += 1;
        }
      });
      if (min * 2 <= length && length <= max * 2) {
        callback();
      } else {
        callback(`只能输入${min}-${max}个汉字`);
      }
    },
    handleDescRules(value, min, max, callback) {
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
      let length = 0;
      let strArr = value.split("");
      strArr.forEach((item) => {
        if (cnReg.test(item)) {
          length += 2;
        } else {
          length += 1;
        }
      });
      if (min <= length && length <= max) {
        callback();
      } else {
        callback(`只能输入${min}-${max}个字符`);
      }
    },
    // 分页操作按钮
    handleOnShowSizeChange(current, pageSize) {
      this.tablePag = {
        page: current,
        size: pageSize,
      };
      this.handleInitTable();
    },
    //作废操作
    handleVoid(list) {
      this.voidOperationStatus = true;
      this.voidId = list.id;
    },
    // 编辑按钮操作
    handleEditTable(list) {
      this.addType = "edit";
      this.policyOperationStatus = true;
      this.queryByIdList = list;
      this.policyOperationForm = {
        ...list,
        advertiserId: { key: list.advertiserId, label: list.advertiserName },
        productId: { key: list.productId, label: list.productName },
        files: list.files == "-" ? undefined : JSON.parse(list.files),
      };
      this.getList();
      this.getProductList({ key: list.advertiserId, label: list.advertiserName });
      this.getInfo({ key: list.productId, label: list.productName });

      setTimeout(() => {
        this.$set(this.policyOperationForm, "advertiserId", {
          key: list.advertiserId,
          label: list.advertiserName,
        });
        this.$set(this.policyOperationForm, "productId", {
          key: list.productId,
          label: list.productName,
        });
        this.$set(this.policyOperationForm, "paymentMedia", +list.paymentMedia);
        this.$set(this.policyOperationForm, "paymentPort", +list.paymentPort);
        this.$set(this.policyOperationForm, "cashAmount", list.cashAmount);
        this.$set(this.policyOperationForm, "displayAmount", list.displayAmount);
        this.$set(this.policyOperationForm, "rebateType", +list.rebateType);
        this.$set(this.policyOperationForm, "rebateRate", list.rebateRate);
        this.$set(
          this.policyOperationForm,
          "files",
          list.files == "-" ? undefined : JSON.parse(list.files)
        );
        this.$set(this.policyOperationForm, "remarks", list.remarks);
        this.$set(this.policyOperationForm, "paymentType", +list.paymentType);
      }, 500);
      // this.policyOperationForm = Object.assign({}, list);
    },

    handleAddSureBtn(data, url) {
      postAction(url, data)
        .then((result) => {
          if (result.code === 200) {
            this.totalAmount = undefined;
            this.rebateData = undefined;
            this.$message.success(result.message);
            this.handlePolicyOperationCancel();
            this.handleAuditCancel();
            this.handleInitTable();
          } else {
            this.$message.error(result.message);
          }
        })
        .catch((error) => {
          console.log(error, "eeee");
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    // 新增政策取消按钮
    handlePolicyOperationCancel() {
      this.policyOperationForm = {};
      this.policyOperationStatus = false;
      this.confirmLoading = false;
      this.writeRebate = false;
      this.showRebate = false;
    },
    // 审核拒绝确定按钮
    handleRejectSure() {
      this.$refs.rejectRuleForm.validate((valid) => {
        console.log(valid);
        if (valid) {
          const params = {
            id: this.tableOnlyId || this.queryByIdList.id,
            type: this.okType,
            value: this.reasonForm.desc,
          };
          this.handleExamineAll(params);
          this.handleRejectCancel();
        } else {
          return false;
        }
      });
    },
    //领导审核理由
    handleVoidOk() {
      this.$refs.rejectRuleForm.validate((valid) => {
        if (valid) {
          const params = {
            policyId: this.voidId,
            delReason: this.reasonForm.desc,
          };

          getAction(urlAcount + "/finance/cwjsPolicyInfo/toVoidpolicy", params)
            .then((result) => {
              if (result.code === 0) {
                this.voidOperationStatus = false;
                this.reasonForm.desc = undefined;
                this.handleInitTable();
              } else {
                this.$message.error(result.message);
              }
            })
            .catch((error) => {
              console.log(error, "eeee");
            })
            .finally(() => {
              this.voidOperationStatus = false;
            });
        } else {
          return false;
        }
      });
    },
    //领导审核理由
    handleLeader() {
      this.$refs.rejectRuleForm.validate((valid) => {
        if (valid) {
          const params = {
            id: this.tableOnlyId || this.queryByIdList.id,
            type: 4,
            value: this.reasonForm.desc,
          };
          this.handleExamineAll(params);
          this.handleRejectCancel();
        } else {
          return false;
        }
      });
    },
    // 审核拒绝取消按钮
    handleRejectCancel() {
      this.okType = 3;
      this.reasonForm.desc = "";
      this.rejectAuditStatus = false;
      this.toLeaderVisible = false;
    },
    toLeader() {
      // this.queryByIdList
      this.toLeaderVisible = true;
      this.postDataAction("/financePayment/rechargeApplication/updateStatus", {
        id: this.queryByIdList.id,
        userId: this.userInfo().id,
        auditStatus: 4,
        files: this.files,
        // temporaryPassage: 1,
      }).then((res) => {
        if (res.success) {
          this.toLeaderVisible = false;
          this.paymentTypeDisable = false;
          this.handleInitTable();
        }
      });
    },
    //撤销
    remove(item) {
      this.getAction("/financePayment/rechargeApplication/delete", { id: item })
        .then((res) => {
          if (res.success) {
            this.$message.success("撤销成功");
            this.handleInitTable();
          }
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    // 复制信息
    handleCopy(item) {
      this.getAction("/financePayment/rechargeApplication/queryById", {
        id: item.id,
      }).then((res) => {
        this.getAction(
          "/financePayment/rechargeApplication/queryRechargeAccountDetails",
          {
            rechargeId: item.id,
          }
        ).then((result) => {
          var data = `
客户名称：${item.advertiserName}
产品：${item.productName}
政策类型：${result.result[0].rebateType == 1 ? "返货" : "返现"}
返点比例: ${result.result[0].rebateRate}
`;
          for (let i = 0; i < result.result.length; i++) {
            data += `
账户名称：${result.result[i].accountName}
账户ID: ${result.result[i].accountId}
现金金额: ${this.allMoney(result.result[i].cashAmount)}
到账金额:${this.allMoney(result.result[i].receivedAmount)}`;
          }
          if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard
              .writeText(data)
              .then(() => {
                this.$message.success("复制成功");
              })
              .catch((err) => {
                this.$message.error("复制失败");
              });
          } else {
            // 创建text area
            const textArea = document.createElement("textarea");
            textArea.value = data;
            // 使text area不在viewport，同时设置不可见
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            return new Promise((resolve, reject) => {
              // 执行复制命令并移除文本框
              document.execCommand("copy") ? resolve() : reject(new Error("出错了"));
              textArea.remove();
            }).then(
              () => {
                this.$message.success("复制成功");
              },
              () => {
                this.$message.error("复制失败");
              }
            );
          }
        });
      });
    },
    // 查看的按钮
    handleLook(list, type) {
      this.files = undefined;
      this.paymentTypeDisable = true;

      this.getAction("/financePayment/rechargeApplication/queryById", {
        id: list.id,
      }).then((res) => {
        this.getAction(
          "/financePayment/rechargeApplication/queryRechargeAccountDetails",
          {
            rechargeId: list.id,
          }
        ).then((result) => {
          this.queryByIdList = {
            ...res.result,
            newFiles: undefined,
            rechargeType: +res.result.rechargeType,
            accountList: result.result,
            type: type,
          };
          console.log(this.queryByIdList);
        });
      });
    },
    // 编辑的按钮
    handleDetail(list, type) {
      this.addType = "edit";
      this.auditPolicyStatus = true;
      this.queryByIdList = {
        ...list,
        newFiles: undefined,
        type: type,
        rechargeType: +list.rechargeType,
        accountList: [],
      };

      this.getNewAdvertiserList();
      this.$set(this.queryByIdList, "advertiserId", list.advertiserId);
      this.getNewProductList(this.queryByIdList.advertiserId);
      this.$set(this.queryByIdList, "productId", list.productId);
      this.getMediaList(this.queryByIdList.productId);
      this.$set(this.queryByIdList, "paymentMedia", list.paymentMedia);
      this.getProjectList(this.queryByIdList.paymentMedia);
      this.$set(this.queryByIdList, "projectId", list.projectId);
      this.getAccountList();
      this.getAction("/financePayment/rechargeApplication/queryRechargeAccountDetails", {
        rechargeId: list.id,
      }).then((res) => {
        this.queryByIdList.accountList.push(...res.result);
      });
      this.rebateData = { rebateType: list.rebateType, rebateRate: list.rebateRate };
    },
    // 查看的取消按钮
    handleCloseAuditPolicy() {
      this.auditPolicyStatus = false;
    },
    editMoneyNew(value, type, index) {
      if (
        type == 1 &&
        !!this.rebateData &&
        (!!this.rebateData.rebateRate || this.rebateData.rebateRate == 0)
      ) {
        this.$set(
          this.queryByIdList.accountList[index],
          "cashAmount",
          this.rebateData.rebateType == 1
            ? Math.floor((value / (1 + this.rebateData.rebateRate / 100)) * 100) / 100
            : Math.floor(value * (1 - this.rebateData.rebateRate / 100) * 100) / 100
        );
      } else if (
        type == 2 &&
        !!this.rebateData &&
        (!!this.rebateData.rebateRate || this.rebateData.rebateRate == 0)
      ) {
        this.$set(
          this.queryByIdList.accountList[index],
          "receivedAmount",
          this.rebateData.rebateType == 1
            ? Math.floor(value * (1 + this.rebateData.rebateRate / 100) * 100) / 100
            : Math.floor((value / (1 - this.rebateData.rebateRate / 100)) * 100) / 100
        );
      } else {
        this.$message.error("暂未返点比例");
      }
    },
    // 查看-审核政策-审核通过-按钮
    handleAuditSure(list) {
      this.$refs.queryByIdList.validate((valid) => {
        if (valid) {
          var that = this;
          var total = this.queryByIdList.accountList
            .map((item) => {
              return item.cashAmount;
            })
            .reduce((o, n) => {
              return +o + +n;
            }, 0);
          var amendsStr = this.amends;
          let names = this.queryByIdList.accountList.map((item) => item["accountId"]);
          let nameSet = new Set(names);

          if (nameSet.size == names.length) {
            const paramsData = {
              ...this.queryByIdList,
              applicanterId: this.userInfo().id,
              userId: this.userInfo().id,
              totalAmount: total,
              amends: amendsStr,
              financialReview: total > +that.totalAmount ? 1 : 0,
              list: this.queryByIdList.accountList.map((item) => {
                return {
                  ...item,
                  rebateType: this.rebateData ? this.rebateData.rebateType : null,
                  rebateRate: this.rebateData ? this.rebateData.rebateRate : null,
                };
              }),
            };
            console.log(paramsData, that.totalAmount);

            this.confirmLoading = true;
            if (
              !!this.rebateData &&
              (!!this.rebateData.rebateRate || this.rebateData.rebateRate == 0)
            ) {
              if (this.addType === "add") {
                this.handleAddSureBtn(
                  paramsData,
                  "/financePayment/rechargeApplication/add"
                );
              } else {
                this.handleAddSureBtn(
                  { ...paramsData },
                  "/financePayment/rechargeApplication/edit"
                );
              }
            } else {
              this.$message.error("暂时不能进行新增\修改操作，请联系管理员！");
            }
          } else {
            this.$message.error("账户ID填写重复，请检查");
          }
        } else {
          return false;
        }
      });
    },
    okFour(data) {
      this.postDataAction(
        "/financePayment/rechargeApplication/updateTemporaryFiles",
        data
      ).then((result) => {
        if (result.code === 200) {
          this.rejectAuditStatus = false;
          this.auditPolicyStatus = false;
          this.paymentTypeDisable = false;
          this.handleInitTable();
          this.$message.success(result.message);
        } else {
          this.$message.error(result.message);
        }
      });
    },
    // 查看-取消
    handleAuditCancel(data) {
      this.queryByIdList = { accountList: [] };
      this.rebateData = undefined;
      this.totalAmount = undefined;
      this.auditPolicyStatus = false;
    },
    //  通过审核
    handleOk() {
      let that = this;
      this.$confirm({
        title: "提示",
        content: "确认该审核通过",
        onOk() {
          if (that.queryByIdList.auditStatus == 4) {
            const paramsFour = {
              id: that.queryByIdList.id,
              files: that.files,
            };
            that.okFour(paramsFour);
          } else {
            const params = {
              id: that.queryByIdList.id,·
              auditStatus:
                that.queryByIdList.auditStatus == 1
                  ? 2
                  : that.queryByIdList.auditStatus == 2
                  ? 3
                  : that.queryByIdList.auditStatus,
              userId: that.userInfo().id,
              files: that.files,
            };
            that.handleExamineAll(params);
          }
        },
      });
    },
    // 修改附件
    handleEditFiles() {
      if (this.editFilesData.length > 0) {
        this.editFileLoading = true;
        this.postDataAction("/financePayment/rechargeApplication/editAll", {
          id: this.editFilesId,
          files: this.editFilesData,
        }).then((res) => {
          if (res.success) {
            this.editFileLoading = false;
            this.editFileVisible = false;
            this.editFilesData = [];
            this.editFilesId = null;
          }else{
            this.$message.error(res.message)
          }
        });
      } else {
        this.$message.error("请上传附件");
      }
    },
    // 审核拒绝
    handleNo() {
      const params = {
        id: this.queryByIdList.id,
        auditStatus: 5,
        userId: this.userInfo().id,
        approvalContent: this.approvalContent,
      };
      this.handleExamineAll(params);
    },
    handleSubmitEdit(list) {},
    // 被拒理由的操作
    handleRejectionReason(val) {
      this.rejectionReasonList = val;
      this.rejectionReasonStatus = true;
    },
    // 被拒理由确定按钮
    handleModeSure() {
      this.rejectionReasonStatus = false;
    },
    // 被拒理由取消按钮
    handleModeCancel() {
      this.rejectionReasonStatus = false;
    },
    // 搜索按钮
    handleQueryList() {
      this.tablePag = {
        page: 1,
        size: 10,
      };
      this.handleInitTable();
    },

    // 重置搜索
    handleResetList() {
      this.configForm = {
        companyId: undefined,
        userName: undefined,
        media: undefined,
        departId: undefined,
        time: [],
        status: undefined,
        type: undefined,
        accountId: undefined,
        amends: undefined,
      };
      this.tablePag = {
        page: 1,
        size: 10,
      };
      this.handleInitTable();
    },
  },
};
</script>
<style lang="less" scoped>
@import "policy-management";
</style>
