<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="代理商" prop="deptId" v-if="userName == 'admin'">
        <el-select v-model="queryParams.deptId" filterable placeholder="请选择代理商" clearable>
          <el-option
            v-for="item in deptOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="提现单号" prop="withdrawNo">
        <el-input
          v-model="queryParams.withdrawNo"
          placeholder="请输入提现单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择申请状态" clearable>
          <el-option
            v-for="dict in dict.type.et_withdraw_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="userName != 'admin'">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:withdraw:add']"
        >申请</el-button>
      </el-col>
      <el-col :span="1.5" v-if="userName != 'admin' && user.appUserId == null" >
        <el-button
          type="success"
          plain
          icon="el-icon-link"
          size="mini"
          @click="bandWxUser"
          v-hasPermi="['system:withdraw:add']"
        >绑定微信用户</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:withdraw:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="withdrawList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="提现id" align="center" prop="id" />-->
      <el-table-column label="代理商" align="center" prop="deptName" v-if="userName == 'admin'"/>
      <el-table-column label="提现单号" align="center" prop="withdrawNo" />
      <el-table-column label="提现金额：元" align="center" prop="amount" />
      <el-table-column label="申请状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.et_withdraw_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applicant" />
      <el-table-column label="微信openid" align="center" prop="wxopenid" />
      <el-table-column label="驳回原因" align="center" prop="rejectReason" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回调状态" align="center" prop="callStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.et_call_status" :value="scope.row.callStatus"/>
        </template>
      </el-table-column>
      <el-table-column v-if="userName == 'admin'" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status == 0"
                     size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleEdit(scope.row)"
                     v-hasPermi="['system:fault:query']"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改提现记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="可用余额">
          <span style="color: red;font-weight: 700">{{balance}}</span> 元
        </el-form-item>
      </el-form>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="提现金额：" prop="amount">
          <el-input style="width: 40%" v-model="form.amount" placeholder="请输入提现金额" /> 元
        </el-form-item>
        <el-form-item v-if="form.amount" label="提示：" style="font-weight: 300;color: red">
          <span class="amoun-tips" >提现金额：{{form.amount}}元，手续费：{{formattedFee}} 元，实际到账：{{actualAmount}} 元</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改提现记录对话框 -->
<!--    <el-dialog :title="title2" :visible.sync="open2" width="500px" append-to-body>-->
<!--      <el-form ref="form2" :model="form2" :rules="rules2" label-width="120px">-->
<!--        <el-form-item label="手机号码" prop="phonenumber">-->
<!--          <el-select-->
<!--            ref="headerSearchSelect"-->
<!--            v-model="form2.phonenumber"-->
<!--            :remote-method="queryPhonenumber"-->
<!--            filterable-->
<!--            default-first-option-->
<!--            remote-->
<!--            :loading="loading2"-->
<!--            placeholder="输入手机号搜索"-->
<!--            class="header-search-select" >-->
<!--            <el-option-->
<!--              v-for="item in options"-->
<!--              :key="item.value"-->
<!--              :label="item.label+'-&#45;&#45;'+item.appName"-->
<!--              :value="item.value">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="submitForm2">确 定</el-button>-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->

    <el-dialog title="提现详细" :visible.sync="open3" width="700px" append-to-body>
      <el-form ref="form3" :model="form3"  label-width="100px" size="mini">
        <el-row>
          <el-col :span="24">
            <el-form-item label="代理商：">{{ form3.deptName }}</el-form-item>
            <el-form-item label="提现单号：">{{ form3.withdrawNo }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="提现金额："><span style="color: red;font-weight: 700">{{ form3.amount }}</span> 元</el-form-item>
            <el-form-item label="申请人：">{{ form3.applicant }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="申请时间：">{{ form3.createTime }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态：">
              <dict-tag :options="dict.type.et_withdraw_status" :value="form3.status"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="驳回原因" prop="rejectReason">
              <el-input v-model="form3.rejectReason" type="textarea" placeholder="请输入驳回原因"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="view == true" @click="open3 = false">关 闭</el-button>
        <el-button v-show="view == false" type="success" @click="pass">通 过</el-button>
        <el-button v-show="view == false" type="danger" @click="reject">拒 绝</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWithdraw, getWithdraw, delWithdraw, addWithdraw, updateWithdraw } from "@/api/system/withdraw";
// import { getDeptByToken, listDept } from '@/api/system/dept'
import { fastSearch } from '@/api/user/user'
import { getUser } from '@/api/system/user'


export default {
  name: "Withdraw",
  dicts: ['et_call_status', 'et_withdraw_status'],
  computed: {
    formattedFee() {
      console.log("handlingCharge===========",this.handlingCharge)
      // 将handlingCharge转换为浮点类型
      let handlingCharge = parseFloat(this.handlingCharge)/1000;
      console.log("handlingCharge1===========", handlingCharge);
      console.log("this.form.amount===========", this.form.amount);
      // 计算手续费
      let fee = this.form.amount * handlingCharge;
      // 保留两位小数，并确保四舍五入
      fee = fee.toFixed(2);

      // 判断手续费是否为0
      if (fee === 0) {
        return '0.00 （免手续费）';
      } else {
        return `${fee} `;
      }
    },
    actualAmount() {
      let amount = this.form.amount;
      let handlingCharge = parseFloat(this.handlingCharge)/1000;
      let fee = this.form.amount * handlingCharge;
      // 四舍五入到两位小数
      fee = Math.round(fee * 100) / 100;
      // 计算实际到账金额并四舍五入到两位小数
      let actual = amount - fee;
      actual = actual.toFixed(2);
      return `${actual} `;
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      deptOptions: [],
      search: '',
      options: [],
      fuse: undefined,
      // 非单个禁用
      single: true,
      loading2: false,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 提现记录表格数据
      withdrawList: [],
      balance: null,
      userName:null,
      user: null,
      view: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      title2: "",
      // 弹出层标题
      open2: false,
      // 是否显示弹出层
      open3: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        withdrawNo: null,
        deptId: null,
        status: null,
        applicant: null,
        phonenumber: null
      },
      // 表单参数
      form: {},
      // 表单参数
      form2: {},
      form3: {},
      // 表单校验
      rules: {
        amount: [
          { required: true, message: "提现金额不能为空", trigger: "blur" },
          { pattern: /^\d+$/, message: '提现金额必须为正整数', trigger: 'blur' },
          // 提现金额不能小于 1
          {
            validator: (rule, value, callback) => {
              if (value < 1) {
                callback(new Error('提现金额不能小于1'));
              } else {
                callback();
              }
            },
            trigger: 'blur',
          },
          // 不能超过  balance 值
          {
            validator: (rule, value, callback) => {
              if (value > this.balance) {
                callback(new Error('提现金额不能超过可用余额'));
              } else {
                callback();
              }
            },
            trigger: 'blur',
          },
        ]
      },
      rules2: {
        phonenumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          // { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
        ]
      }
    };
  },
  created() {
    console.log("当前用户信息：",this.$store.state.user.id)
    this.userName = this.$store.state.user.name;
    let userId = this.$store.state.user.id;
    getUser(userId).then(response => {
      this.user = response.data;
    });
    this.getList();
    if(this.userName === 'admin'){
      listDept({status: '0',pageNum:1,pageSize:999  }).then(response => {
        this.deptOptions = response.data;
      });
    }
  },
  methods: {
    /** 审核 */
    handleEdit(row) {
      this.open3 = true;
      this.form3 = row;
      this.view = false;
    },
    /** 通过 */
    pass(){
      this.$refs["form3"].validate(valid => {
        if (valid) {
          if (this.form3.id != null) {
            this.form3.status = "1";
            console.log("---------"+JSON.stringify(this.form3))
            updateWithdraw(this.form3).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open3 = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 拒绝 */
    reject(){
      // console.log("-===========",this.form3.rejectReason)
      if(this.form3.rejectReason == undefined || this.form3.rejectReason == ''){
        this.$modal.msgError("驳回原因不能为空");
        return
      }
      this.$refs["form3"].validate(valid => {
        if (valid) {
          if (this.form3.id != null) {
            this.form3.status = "2";
            updateWithdraw(this.form3).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open3 = false;
              this.getList();
            });
          }
        }
      });
    },
    queryPhonenumber(query) {
      console.log("query:",query)
      if (query !== '') {
        this.loading2 = true;
        setTimeout(() => {
          this.loading2 = false;
          fastSearch({"phonenumber":query}).then(response => {
              this.options =  response.data;
            }
          );
        }, 200);
      } else {
        this.options = []
      }
    },
    /** 查询提现记录列表 */
    getList() {
      this.loading = true;
      listWithdraw(this.queryParams).then(response => {
        this.withdrawList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        withdrawNo: null,
        amount: null,
        deptId: null,
        status: null,
        applicant: null,
        wxopenid: null,
        createTime: null,
        callStatus: null
      };
      this.form2 = {
        appUserId: null,
      };
      this.resetForm("form");
      this.resetForm("form2");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // //查询余额
      // getDeptByToken().then(response => {
      //   this.balance = response.data.balance;
      //   this.handlingCharge = response.data.handlingCharge;
      // });
      this.reset();
      this.open = true;
      this.title = "申请提现";
    },
    bandWxUser(){
      this.reset();
      this.open2 = true;
      this.title2 = "绑定微信用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWithdraw(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改提现记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWithdraw(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWithdraw(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // submitForm2: function() {
    //   let form2 = this.form2
    //   this.$refs['form2'].validate(valid => {
    //     if (valid) {
    //       this.$modal.confirm('是否确认绑定？').then(function() {
    //         return bandAppUser({appUserId:form2.phonenumber})
    //       }).then(() => {
    //         // 刷新页面
    //         location.reload()
    //         this.$modal.msgSuccess('操作成功')
    //       }).catch(() => {
    //       })
    //     }
    //   })
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除提现记录编号为"' + ids + '"的数据项？').then(function() {
        return delWithdraw(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/withdraw/export', {
        ...this.queryParams
      }, `withdraw_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss">
.el-select {
  .el-input__inner{
    color: red;
  }

}
.el-input{
  .el-input__inner{
    color: red;
  }
}
.amoun-tips{
  color: red;
  font-size: 12px;
  font-weight: 700;
}
</style>
