<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="areaId" v-if="userName == 'admin'">
        <el-select v-model="queryParams.areaId" filterable placeholder="请选择运营区" clearable>
          <el-option
            v-for="item in areaOptions"
            :key="item.areaId"
            :label="item.areaName"
            :value="item.areaId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联订单号" label-width="90" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入关联订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="第三方交易单号" label-width="100" prop="outTradeNo">
        <el-input
          v-model="queryParams.outTradeNo"
          placeholder="请输入第三方交易单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收支类型" prop="type">
        <el-select style="width: 100px" v-model="queryParams.type" placeholder="请选择收支类型" clearable>
          <el-option
            v-for="dict in dict.type.et_flow_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:withdraw:add']"
        >申请</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="flowList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="交易时间" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="区域" align="center" prop="areaName" />
      <el-table-column label="所属人" align="center" prop="owner" >
        <template slot-scope="scope">
          <router-link :to="'/system/dept/index/' + scope.row.owner" class="link-type">
            <span>{{ scope.row.owner }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="关联订单号" width="180" align="center" prop="orderNo" />
      <el-table-column label="第三方交易单号" width="180" align="center" prop="outTradeNo" />
      <el-table-column label="收支类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.et_flow_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="业务类型" align="center" prop="busType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.et_business_type" :value="scope.row.busType"/>
        </template>
      </el-table-column>
      <el-table-column label="交易金额" align="center" prop="amount" :formatter="formatAmount"/>
      <el-table-column label="支付手续费" align="center" prop="handlingCharge" :formatter="formatAmount"/>
      <el-table-column label="平台服务费" align="center" prop="platformServiceFee" :formatter="formatAmount"/>
      <el-table-column label="账变金额" align="center" prop="operatorDividend" :formatter="formatAmount"/>
      <el-table-column label="运营商结余" align="center" prop="operatorBalance" :formatter="formatAmount"/>
<!--      <el-table-column label="合伙人分账" align="center" prop="partnerDividend" :formatter="formatAmount"/>-->
      <el-table-column label="支付方式" align="center" prop="payType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.et_pay_type" :value="scope.row.payType"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.et_flow_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.busType == '5' && scope.row.status == '0'"
                     size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleEdit(scope.row)"
                     v-hasPermi="['system:flow:audit']"
          >审核</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="运营商" prop="operator" v-if="userName == 'admin'">
            <el-select v-model="form.deptId" clearable placeholder="请选择运营商">
              <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="提现方式">
            <el-radio-group v-model="form.method">
              <el-radio
                v-for="dict in dict.type.et_withdraw_method"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="提现金额：" prop="amount">
            <el-input style="width: 40%" v-model="form.amount" placeholder="请输入提现金额" /> 元
          </el-form-item>
          <el-form-item label="可用余额">
            <span style="color: red;font-weight: 700">{{balance}}</span> 元
          </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="提现详细" :visible.sync="open3" width="1000px" append-to-body>
      <el-form ref="form3" :model="form3"  label-width="100px" size="mini">
        <el-row>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="申请人：">{{ form3.owner }}</el-form-item>
              <el-form-item label="区域：">{{ form3.areaName }}</el-form-item>
              <el-form-item label="提现金额："><span style="font-weight: 700">{{ form3.amount + form3.handlingCharge  }}</span> 元</el-form-item>
              <el-form-item label="支付手续费："><span style="font-weight: 700">{{ form3.handlingCharge }}</span> 元</el-form-item>
              <el-form-item label="实际到账："><span style="color: red;font-weight: 700">{{ form3.amount }}</span> 元</el-form-item>
              <el-form-item label="运营商结余："><span style="font-weight: 700">{{ form3.operatorBalance }}</span> 元</el-form-item>
              <el-form-item label="申请时间：">{{ form3.createTime }}</el-form-item>
              <el-form-item label="状态：">
                <dict-tag :options="dict.type.et_flow_status" :value="form3.status"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <img :src="collectionCode" alt="收款码" style="max-width: 100%; height: auto;">
            </el-col>
          </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 { listFlow, getFlow, delFlow, updateFlow, withdraw, rejectWithdraw } from '@/api/system/flow'
import { optionselect as getAreaOptionselect } from '@/api/system/area'
  import { getDept, getDeptByToken, listDept, listDept2 } from '@/api/system/dept'

export default {
  name: "Flow",
  dicts: ['et_business_type', 'et_pay_type', 'et_flow_type','et_flow_status','et_withdraw_method'],
  watch: {
    'form.deptId': function(newVal) {
      this.getDept(newVal);
    },
  },
  computed: {
    formattedFee() {
      let fee;
      if(this.handlingChargeType === '1'){
        let handlingCharge = parseFloat(this.handlingCharge)/1000;
        // 计算手续费
        let fee1 = this.form.amount * handlingCharge;
        // 保留两位小数，并确保四舍五入
        fee = fee1.toFixed(2);
      }else{
        fee = parseFloat(this.handlingCharge);
      }
      // 判断手续费是否为0
      if (fee === 0) {
        return '0.00 （免手续费）';
      } else {
        return `${fee} `;
      }
    },
    actualAmount() {
      let amount = this.form.amount;
      let fee;
      if(this.handlingChargeType === '1'){
        let handlingCharge = parseFloat(this.handlingCharge)/1000;
        let fee1 = this.form.amount * handlingCharge;
        // 四舍五入到两位小数
        fee = Math.round(fee1 * 100) / 100;
        // 计算实际到账金额并四舍五入到两位小数
      }else{
        fee = parseFloat(this.handlingCharge);
      }
      let actual = amount - fee;
      actual = actual.toFixed(2);
      return `${actual} `;
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      deptOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      areaOptions: [],
      balance: null,
      // 选中数组
      userName: undefined,
      // 日期范围
      dateRange: [],
      view: false,
      // 总条数
      total: 0,
      // 资金流水表格数据
      flowList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open3: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        areaId: null,
        orderNo: null,
        outTradeNo: null,
        type: null,
        busType: '',
        typeList: '5,6',
        amount: null,
        handlingCharge: null,
        operatorDividend: null,
        operatorBalance: null,
        partnerDividend: null,
        payType: null,
      },
      // 表单参数
      form: {},
      form3: {},
      collectionCode:null,
      // 表单校验
      rules: {
        amount: [
          { required: true, message: "提现金额不能为空", trigger: "blur" },
          { pattern: /^\d+$/, message: '提现金额必须为正整数', trigger: 'blur' },
          // 不能超过  balance 值
          {
            validator: (rule, value, callback) => {
              if (value > this.balance) {
                callback(new Error('提现金额不能超过可用余额'));
              } else {
                callback();
              }
            },
            trigger: 'blur',
          },
        ]
      }
    };
  },
  created() {
    // console.log("当前用户信息：",this.$store.state.user.name)
    this.userName = this.$store.state.user.name;
    this.getList();
    this.getAreaList();
    if(this.userName === 'admin'){
      listDept2({status: '0',pageNum:1,pageSize:999 }).then(response => {
        this.deptOptions = response.rows;
      });
    }
  },
  methods: {
    getDept(deptId){
      getDeptByToken(deptId).then(response => {
        this.balance = response.data.balance;
        this.handlingCharge = response.data.handlingCharge;
        this.handlingChargeType = response.data.handlingChargeType;
        this.form.amount = 0;
        // console.log("11111handlingCharge===========",this.handlingCharge)
        // console.log("22222handlingChargeType===========",this.handlingChargeType)
      });
    },
    /** 审核 */
    handleEdit(row) {
      getDept(row.ownerId).then(response => {
        this.collectionCode = response.data.collectionCode;
        this.open3 = true;
        this.form3 = row;
        this.view = false;
      });
    },
    /** 通过 */
    pass(){
      this.$refs["form3"].validate(valid => {
        if (valid) {
          if (this.form3.flowId != null) {
            this.form3.status = "8";
            // console.log("---------"+JSON.stringify(this.form3))
            updateFlow(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.flowId != null) {
            rejectWithdraw(this.form3).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open3 = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 查询字典类型列表 */
    getAreaList() {
      getAreaOptionselect().then(response => {
        this.areaOptions = response.data;
      });
    },
    formatAmount(row, column) {
      const key = column.property;
      return parseFloat(row[key] || 0).toFixed(2);
    },
    /** 查询资金流水列表 */
    getList() {
      this.loading = true;
      listFlow(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.flowList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        flowId: null,
        areaId: null,
        orderNo: null,
        outTradeNo: null,
        type: null,
        busType: null,
        amount: null,
        handlingCharge: null,
        handlingChargeType: null,
        operatorDividend: null,
        operatorBalance: null,
        partnerDividend: null,
        payType: null,
        createTime: null,
        method: "1"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.flowId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      if(this.userName != 'admin'){
        //查询余额
        getDeptByToken().then(response => {
          this.balance = response.data.balance;
          this.handlingCharge = response.data.handlingCharge;
          this.handlingChargeType = response.data.handlingChargeType;
        });
      }
      this.reset();
      this.open = true;
      this.title = "申请提现";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const flowId = row.flowId || this.ids
      getFlow(flowId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资金流水";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          withdraw(this.form).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const flowIds = row.flowId || this.ids;
      this.$modal.confirm('是否确认删除资金流水编号为"' + flowIds + '"的数据项？').then(function() {
        return delFlow(flowIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/flow/export', {
        ...this.queryParams
      }, `flow_${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;
  }

.el-dialog__body {
  padding: 0px 20px !important;
}
</style>
