<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="accStatusList">
            <el-select v-model="queryParams.accStatusList" multiple style="width: 240px" clearable> 
                <el-option label="正常" value="1"></el-option>
                <el-option label="停用" value="2"></el-option>  
            </el-select>   
        </el-form-item>
        <el-form-item label="所属组织" prop="orgIdList">  
            <el-cascader v-model="queryParams.orgIdList"
            :options="deptOptions" :filterable="true" style="width: 240px" :show-all-levels="false"
            :props="{ 
                multiple: true,
                emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                value:'id',label:'label' 
            }" clearable collapse-tags >
            </el-cascader> 
        </el-form-item> 
        <el-form-item label="关键字" prop="keyword">
            <el-input v-model="queryParams.keyword" placeholder="请输入用户姓名，编号，手机号" maxlength="20" clearable style="width: 240px"/>
        </el-form-item>
        <br>
        <el-form-item label="钱包类型" prop="walletType">
            <el-select v-model="queryParams.walletType" style="width: 240px" clearable> 
                <el-option label="账户总余额" value="0"></el-option>
                <el-option label="个人钱包" value="1"></el-option>
                <el-option label="补贴钱包" value="2"></el-option> 
                <el-option label="红包" value="3"></el-option> 
            </el-select>   
        </el-form-item>
        <el-form-item label="最小金额" prop="walletMinAmount">
            <el-input
                v-model="queryParams.walletMinAmount"
                placeholder="请输入最小金额" style="width: 240px"  @input="(v)=>(queryParams.walletMinAmount=v.replace(/[^\d.]/g,''))">
                <template slot="append">元</template>
            </el-input>
        </el-form-item>
        <el-form-item label="最大金额" prop="walletMaxAmount">
            <el-input
                v-model="queryParams.walletMaxAmount"
                placeholder="请输入最大金额" style="width: 240px"  @input="(v)=>(queryParams.walletMaxAmount=v.replace(/[^\d.]/g,''))">
                <template slot="append">元</template>
            </el-input>
        </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 
            size="mini"
            @click="handleBatchEdit"
          >批量修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-badge :value="cancelCount" class="item">
            <el-button  size="mini" @click="openCancelAcc" >注销用户</el-button>
          </el-badge> 
        </el-col>  
        <el-col :span="1.5">
          <el-badge :value="expiredCount" class="item">
            <el-button  size="mini" @click="openExpiredAcc" >过期用户</el-button>
          </el-badge>
        </el-col>  
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row> 
      <el-table v-loading="loading" :data="tableListData" height="800" :span-method="objectSpanMethod">
        <el-table-column label="序号" align="center" width="80" type="index">
            <template scope="scope">
                <span v-if="!scope.row.custId">合计：</span>
                <span v-else>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
            </template> 
        </el-table-column> 
        <el-table-column label="用户编号" align="center" prop="custNum" :show-overflow-tooltip="true" width="120" fixed="left"/>
        <el-table-column label="用户姓名" align="center" prop="custName" :show-overflow-tooltip="true" width="120" fixed="left"/>
        <el-table-column label="用户手机号" align="center" prop="mobile" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="所属组织" align="center" prop="orgFullName" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="用户类别" align="center" prop="psnTypeName" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="账户总余额" align="center" prop="accBalTotal" :show-overflow-tooltip="true" width="120">
          <template slot-scope="scope">
                <span>{{ (scope.row.accBalTotal/100).toFixed(2) }}</span>
            </template> 
        </el-table-column>
        <el-table-column label="可用总余额" align="center" prop="accAvailableBal" :show-overflow-tooltip="true" width="120">
          <template slot-scope="scope">
                <span>{{ (scope.row.accAvailableBal/100).toFixed(2) }}</span>
            </template> 
        </el-table-column>
        <el-table-column label="个人钱包余额" align="center" prop="walletBal" :show-overflow-tooltip="true" width="120">
          <template slot-scope="scope">
                <span>{{ (scope.row.walletBal/100).toFixed(2) }}</span>
            </template> 
        </el-table-column>
        <el-table-column label="补贴钱包余额" align="center" prop="subsidyBal" :show-overflow-tooltip="true" width="120">
          <template slot-scope="scope">
                <span>{{ (scope.row.subsidyBal/100).toFixed(2) }}</span>
            </template> 
        </el-table-column>
        <el-table-column label="红包余额" align="center" prop="redEnvelope" :show-overflow-tooltip="true" width="120">
          <template slot-scope="scope">
                <span>{{ (scope.row.redEnvelope/100).toFixed(2) }}</span>
            </template> 
        </el-table-column>
        <el-table-column label="冻结金额" align="center" prop="accFreezeBalTotal" :show-overflow-tooltip="true" width="120">
          <template slot-scope="scope">
                <span>{{ (scope.row.accFreezeBalTotal/100).toFixed(2) }}</span>
            </template> 
        </el-table-column>
        <el-table-column label="个人钱包允许最低金额" align="center" prop="minWalletBalLimit" :show-overflow-tooltip="true" width="160">
          <template slot-scope="scope">
                <span>{{ (scope.row.minWalletBalLimit/100).toFixed(2) }}</span>
            </template> 
        </el-table-column>
        <el-table-column label="补贴钱包允许最低金额" align="center" prop="minSubBalLimit" :show-overflow-tooltip="true" width="160">
          <template slot-scope="scope">
                <span>{{ (scope.row.minSubBalLimit/100).toFixed(2) }}</span>
            </template> 
        </el-table-column>
        <el-table-column label="账户状态" align="center" prop="accStatusName" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="账户有效期" align="center" prop="endDate" :show-overflow-tooltip="true" width="150"/>

        
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope" v-if="scope.$index!=10"> 
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)" 
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete" v-if="scope.row.accStatus==1"
              @click="handleUpdateState(scope.row,2)" 
            >停用</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit" v-if="scope.row.accStatus==2"
              @click="handleUpdateState(scope.row,1)" 
            >启用</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="800px" append-to-body>
        <div style="width: 100%;height: 600px;overflow-y: auto;">
            <el-descriptions class="margin-top" title="账户信息" :column="2" size="small" border>  
                <el-descriptions-item>
                    <template slot="label">用户编号</template>
                    {{form.custNum}}
                </el-descriptions-item> 
                <el-descriptions-item>
                    <template slot="label">用户姓名</template>
                    {{ form.custName }}
                </el-descriptions-item>


                <el-descriptions-item>
                    <template slot="label">用户手机号</template>
                    {{ form.mobile }}
                </el-descriptions-item> 
                <el-descriptions-item>
                    <template slot="label">账户状态</template>
                    {{ form.accStatusName }}
                </el-descriptions-item>


                <el-descriptions-item>
                    <template slot="label">所属组织</template>
                    {{ form.orgFullName }}
                </el-descriptions-item>
            </el-descriptions>
            <el-descriptions class="margin-top" title="账户钱包" :column="2" size="small" border> 
                <el-descriptions-item>
                    <template slot="label">账户总余额</template>
                    {{ (form.accBalTotal/100).toFixed(2) }}
                </el-descriptions-item> 
                <el-descriptions-item>
                    <template slot="label">可用总余额</template>
                    {{ (form.accAvailableBal/100).toFixed(2) }}
                </el-descriptions-item> 
                <el-descriptions-item>
                    <template slot="label">个人钱包余额</template>
                    {{ (form.walletBal/100).toFixed(2) }}
                </el-descriptions-item> 
                <el-descriptions-item>
                    <template slot="label">补贴钱包余额</template>
                    {{ (form.subsidyBal/100).toFixed(2) }}
                </el-descriptions-item> 
                <el-descriptions-item>
                    <template slot="label">红包余额</template>
                    {{ (form.redEnvelope/100).toFixed(2) }}
                </el-descriptions-item> 
                <el-descriptions-item>
                    <template slot="label">冻结金额</template>
                    {{ (form.accFreezeBalTotal/100).toFixed(2) }}
                </el-descriptions-item>
            </el-descriptions>
            <div style="margin: 10px 0;font-weight: bold;font-size: 16px;color: #000;">账户允许最低余额与有效期</div>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
              <el-form-item label="个人钱包" prop="walletLimitBalance">
                <el-input  v-model="form.walletLimitBalance" placeholder="请输入允许最低余额" maxlength="30" clearable style="width: 300px;"
                    @input="(v)=>(form.walletLimitBalance=Number(v.replace(/[^\d.]/g,'')))"/>
              </el-form-item>  
              <el-form-item label="补贴钱包" prop="subLimitBalance">
                <el-input  v-model="form.subLimitBalance" placeholder="请输入允许最低余额" maxlength="30" clearable style="width: 300px;"
                    @input="(v)=>(form.subLimitBalance=Number(v.replace(/[^\d.]/g,'')))"/>
              </el-form-item>
              <el-form-item label="有账户有效期" prop="accEndDate">
                <el-date-picker
                  v-model="form.accEndDate"
                  type="date" :picker-options="pickerOptions" value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
                            
              </el-form-item> 
  
  
           
            </el-form>
        </div>
        
        <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="openBatch" width="900px" append-to-body>
        <div style="width: 100%;height: 600px;overflow-y: auto;">
          <div style="height: 30px;padding-left: 10px;line-height: 30px;margin: 10px 0;font-size: 14px;color: #000;background: #e7f0fa;border-left: 3px solid #4b80fd;">第一步：选择用户</div>
            <el-form :model="dialogParams" ref="dialogParams" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="" prop="keyword">
                  <el-input v-model="dialogParams.keyword" placeholder="请输入用户姓名，编号，手机号" maxlength="20" clearable style="width: 240px"/>
              </el-form-item>
              <el-form-item label="" prop="orgIdList">  
                  <el-cascader v-model="dialogParams.orgIdList"
                  :options="deptOptions" :filterable="true" style="width: 240px" :show-all-levels="false"
                  placeholder="所属组织"
                  :props="{ 
                      multiple: true,
                      emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                      checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                      value:'id',label:'label' 
                  }" clearable collapse-tags >
                  </el-cascader> 
              </el-form-item> 
              <el-form-item label="" prop="psnType">
                  <el-select v-model="dialogParams.psnType" placeholder="用户类别" style="width: 240px" clearable> 
                    <el-option
                        v-for="dict in dict.type.user_psn_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="Number(dict.value)"
                      />
                  </el-select>   
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDialogQuery">搜索</el-button> 
              </el-form-item>
            </el-form> 
            <el-table :data="dialogTableData" height="200" ref="multipleTable" :row-key="(row)=>{return row.accId}" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center" :reserve-selection="true"/>
              <el-table-column label="用户编号" align="center" prop="custNum" :show-overflow-tooltip="true"  />
              <el-table-column label="用户姓名" align="center" prop="custName" :show-overflow-tooltip="true" />
              <el-table-column label="用户手机号" align="center" prop="mobile" :show-overflow-tooltip="true" />
              <el-table-column label="所属组织" align="center" prop="orgFullName" :show-overflow-tooltip="true" />
              <el-table-column label="用户类别" align="center" prop="psnTypeName" :show-overflow-tooltip="true"/>
            </el-table>
            <pagination
              v-show="dialogTotal>0"
              :total="dialogTotal"
              :page.sync="dialogParams.pageNum"
              :limit.sync="dialogParams.pageSize"
              @pagination="getDialogList"
            />
          <div style="height: 30px;padding-left: 10px;line-height: 30px;margin: 20px 0;font-size: 14px;color: #000;background: #e7f0fa;border-left: 3px solid #4b80fd;">第二步：修改最低余额和账户有效期</div>
            <el-form ref="batchForm" :model="batchForm" label-width="100px">
              <el-form-item label="个人钱包" prop="walletLimitBalance">
                <el-input  v-model="batchForm.walletLimitBalance" placeholder="请输入允许最低余额" maxlength="30" clearable style="width: 300px;"
                    @input="(v)=>(batchForm.walletLimitBalance=Number(v.replace(/[^\d.]/g,'')))"/>
              </el-form-item>  
              <el-form-item label="补贴钱包" prop="subLimitBalance">
                <el-input  v-model="batchForm.subLimitBalance" placeholder="请输入允许最低余额" maxlength="30" clearable style="width: 300px;"
                    @input="(v)=>(batchForm.subLimitBalance=Number(v.replace(/[^\d.]/g,'')))"/>
              </el-form-item>
              <el-form-item label="有账户有效期" prop="accEndDate">
                <el-date-picker
                  v-model="batchForm.accEndDate"
                  type="date" :picker-options="pickerOptions" value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker> 
              </el-form-item> 
  
  
           
            </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmBatchEdit">确 定</el-button>
          <el-button @click="openBatch=false">取 消</el-button>
        </div>
      </el-dialog>





    </div>
  </template>
  
  <script>
  import { deptTreeSelect } from '@/api/system/user'
  import { accInfoOperateCountApi, accInfoPageApi, accInfoSumPageApi,updateAccInfoSingleApi,updateAccInfoBatchApi,updateAccStateApi } from "@/api/accountCenter/manager";
  
  export default {
    name: "",
    dicts: ['user_psn_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        //表格数据
        tableListData: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false, 
        //下拉选数据
        deptOptions:[],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          accStatusList:[], 
          orgIdList:[],  
          hasSum:true,
          keyword:null,
          walletType:null,
          walletMinAmount:null, 
          walletMaxAmount:null,
        },
        cancelCount:0,
        expiredCount:0,
        // 表单参数
        form: {},
        pickerOptions:{                                 
            //禁用当前日期之前的日期
            disabledDate(time) {
            //Date.now()是javascript中的内置函数，它返回自1970年1月1日00:00:00 UTC以来经过的毫秒数。
               return time.getTime() < Date.now() - 8.64e7;
            }
        },
        // 表单校验
        rules: {
        },
        openBatch:false,
        dialogParams: {
          pageNum: 1,
          pageSize: 10,
          accStatusList:[],
          orgIdList:[], 
          hasSum:true,
          keyword:null,
          psnType:null
        },
        dialogTableData:[],
        dialogTotal: 0,
        batchForm:{
          accEndDate:"",
          subLimitBalance:0,
          walletLimitBalance:0
        },
        batchIds:[]
        
      };
    },
    created() {
        this.getDeptTree()
        this.getAccOperateCount()
        this.getList();
    },
    methods: {
        /** 查询部门下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then((response) => {
                this.deptOptions = this.filterTree(response.data)
            })
        },
        filterTree(nodes) {
            return nodes
                .map((node) => {
                    if (node.children) {
                        node.children = this.filterTree(node.children)
                    }
                    return node
                })
                .filter((node) => node.status !== '1')
        },
        //注销过期用户数量
        getAccOperateCount(){
          accInfoOperateCountApi().then(response => {
              this.cancelCount = response.data.cancelCount
              this.expiredCount = response.data.expiredCount
          });
        },
        
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() { 
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 查询列表 */
        getList() {
            console.log(this.queryParams)
            this.loading = true;
            let param = {
              "current": this.queryParams.pageNum, 
              "size": this.queryParams.pageSize,
              "accStatusList": this.queryParams.accStatusList,
              "orgIdList": this.queryParams.orgIdList, 
              "hasSum": this.queryParams.hasSum,
              "keyword": this.queryParams.keyword,
              "walletType": this.queryParams.walletType,
              "walletMinAmount": Number(this.queryParams.walletMinAmount)*100,
              "walletMaxAmount": Number(this.queryParams.walletMaxAmount)*100
            } 
            accInfoPageApi(param).then(response => {
                this.tableListData = response.data.pageVO.records;
                this.total = Number(response.data.pageVO.total);
                this.loading = false;
            });
            accInfoSumPageApi(param).then(response => {
                this.tableListData.push(response.data.sumVO)   
            });
        },
        // 合并单元格 rowIndex=行数  columnIndex=列数  
        // 这里是合并table的除表头外的第一行的第二列 + 除表头外的第二行的第二列 
        // 注意列数和行数从 0 开始
        objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
            // if (rowIndex === 0 && columnIndex == 0) {
            //     let rowspan = 0
            //     let colspan = 0
            //     return { rowspan, colspan }
            // }
            // 解决偏移的重要代码
            // 重点在 else if 判断必须加因为合并单元格数据会出现偏移、
            // 否则如果是 第二行 的 第二列 那么隐藏原有第二行 的 第二列的数据使他隐藏
            // else if (rowIndex === 0 && columnIndex < 5) {
            //     return {
            //         rowspan: 11,  
            //         colspan: 0  
            //     }
            // }
        }, 
        /** 停用(启用)按钮操作 */
        handleUpdateState(row,state){
          let param = {
            accStatus:state,
            custId:row.custId
          }
          let str = ''
          if(state==1){
            str = "是否确认启用账户？"
          }
          if(state==2){
            str = "是否确认停用账户？"
          }
          this.$modal.confirm(str+'').then(function() {
                return updateAccStateApi(param);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("操作成功");
            }).catch(() => {}); 
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.form = Object.assign({}, row) 
            this.$set(this.form,"accEndDate",row.endDate)
            this.$set(this.form,"subLimitBalance",(row.minSubBalLimit/100).toFixed(2))
            this.$set(this.form,"walletLimitBalance",(row.minWalletBalLimit/100).toFixed(2))
            this.open = true;
            this.title = "修改";
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {};
            this.resetForm("form");
        }, 
        /** 提交按钮 */
        submitForm: function() {
            this.$refs["form"].validate(valid => {
            if (valid) {
              let param = {
                ...this.form,
                subLimitBalance:this.form.subLimitBalance*100,
                walletLimitBalance:this.form.walletLimitBalance*100
              }
              updateAccInfoSingleApi(param).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
              }); 
            }
            });
        },
        //批量修改弹窗
        handleBatchEdit() {
          this.resetForm("dialogParams");
          this.getDialogList()
          this.batchIds = []
          
          this.batchForm = {
            accEndDate:"",
            subLimitBalance:0,
            walletLimitBalance:0
          }
          this.resetForm("batchForm");
          this.openBatch = true;
          this.$refs.multipleTable.clearSelection() 
        },
        //弹窗搜索
        handleDialogQuery(){
          this.dialogParams.pageNum = 1;
          this.getDialogList();
        },
        //批量弹窗表格查询
        getDialogList(){
          let param = {
              "current": this.dialogParams.pageNum, 
              "size": this.dialogParams.pageSize,
              "accStatusList": this.dialogParams.accStatusList,
              "orgIdList": this.dialogParams.orgIdList, 
              "hasSum": this.dialogParams.hasSum,
              "keyword": this.dialogParams.keyword,
              "psnType": this.dialogParams.psnType
            } 
            accInfoPageApi(param).then(response => {
                this.dialogTableData = response.data.pageVO.records;
                this.dialogTotal = Number(response.data.pageVO.total); 
            });
        },
        //批量弹窗勾选
        handleSelectionChange(selection){
          this.batchIds = selection.map((item) => item.custId)  
        },
        //批量修改提交
        confirmBatchEdit(){
          console.log(this.batchIds)
          console.log(this.batchForm)
          if(this.batchIds.length>0){ 
            let param = { 
              accEndDate:this.batchForm.accEndDate,
              subLimitBalance:this.batchForm.subLimitBalance*100,
              walletLimitBalance:this.batchForm.walletLimitBalance*100,
              custIdList:this.batchIds 
            }
            updateAccInfoBatchApi(param).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.openBatch = false;
                    this.getList();
            });
          }else{
            this.$modal.msgError("请先勾选账户！");
          }

        },
        //注销用户
        openCancelAcc(){
          this.$router.push('/accountCenter/account/logoff')
        },
        //过期用户
        openExpiredAcc(){
          this.$router.push('/accountCenter/account/expired')
          
        }, 
        
    }
  };
  </script>
  