<template>
  <div class="app-container" v-loading="loading">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" >
      <el-form-item label="人员名称:" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          placeholder="请输入人员名称"
          clearable
          size="medium"
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号:" prop="phone">
        <el-input
          v-model.trim="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          size="medium"
          style="width: 140px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卡号:" prop="card">
        <el-input
          v-model.trim="queryParams.card"
          placeholder="请输入卡号"
          clearable
          size="medium"
          style="width: 140px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item class="right">
        <el-button plain  size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
      <br>
      <el-form-item>
        <el-button plain size="mini" @click="synchroPersonnel" v-hasPermi="['recharge:batch:synchro']">人员信息同步</el-button>
        <el-button plain size="mini" @click="batchChange(1)" v-hasPermi="['recharge:batch:binding']">批量绑定</el-button>
        <el-button plain size="mini" @click="batchChange(0)" v-hasPermi="['recharge:batch:relieve']">批量解除</el-button>
        <el-button plain size="mini" @click="handleExport" v-hasPermi="['recharge:batch:recharge']">下载充值模板</el-button>
        <el-upload
          ref="upload"
          class="upload-demo"
          action="#"
          :limit = 1
          :on-change="handleChange"
          :auto-upload="false"
          accept=".xlsx,.xls"
          style="display:inline-block;margin-left:10px;vertical-align: top;"
          v-hasPermi="['recharge:batch:recharge']"
          >
          <el-button size="mini" plain>上传充值文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <el-table  :data="adminList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="50" align="left" />
      <el-table-column label="id" align="left" prop="id"  show-overflow-tooltip />
      <el-table-column label="人员名称" align="left" prop="name"  show-overflow-tooltip />
      <el-table-column label="部门" align="left" prop="dept"  show-overflow-tooltip />

      <!-- <el-table-column label="人员信息" align="left" prop="identity"  show-overflow-tooltip /> -->
      <el-table-column label="手机号" align="left" prop="contacts"  show-overflow-tooltip />
      <el-table-column label="卡号" align="left" prop="cardId"  show-overflow-tooltip />
      <el-table-column label="余额（元）" align="left" prop="balance"  show-overflow-tooltip >
        <template slot-scope="scope">
          {{Number(scope.row.balance).toFixed(2) || '0.00'}}
        </template>
      </el-table-column>
      <el-table-column label="充值到账比例" align="left" prop="proportion"  show-overflow-tooltip >
         <template slot-scope="scope">
          {{scope.row.proportion  ||   1}}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="createTime"  show-overflow-tooltip />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            class="hongs"
            @click="radio(scope.row)"
            v-hasPermi="['recharge:role:wz']"
          >微信、支付宝充值</el-button>
          <el-button
            size="mini"
            type="text"
            class="lvs"
            @click="cash(scope.row)"
            v-hasPermi="['recharge:role:x']"
          >现金</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 报表异常信息-->
    <el-dialog   :title="title" :visible.sync="open" width="700px" append-to-body :before-close="cancel" :close-on-click-modal="false"  >
      <el-table  :data="errList" @selection-change="handleSelectionChange" height="500px">
      <el-table-column label="序号" align="left"  show-overflow-tooltip min-width="50px">
        <template slot-scope="scop">
          {{scop.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="left" prop="userName"  show-overflow-tooltip />
      <el-table-column label="手机号" align="left" prop="userPhone"  show-overflow-tooltip />
      <el-table-column label="订单金额（元）" align="left" prop="money"  show-overflow-tooltip >
        <template slot-scope="scope">
          <span>{{scope.row.money.toFixed(2) || "0.00"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="异常提示" align="left" prop="errorMessage"  show-overflow-tooltip min-width="150%">
        <template slot-scope="scop">
          <span class="danger ">{{scop.row.errorMessage}}</span>
        </template>
      </el-table-column>
    </el-table>
    </el-dialog>

    <!-- 批量绑定 -->
    <el-dialog   :title="title" :visible.sync="open1" width="600px" append-to-body :before-close="cancel" :close-on-click-modal="false"  >
      <el-form ref="queryParams" :model="queryParams"  :rules="rules" label-width="120px" >
        <el-form-item label="到账比例：" prop="id">
          <el-select v-model="queryParams.id" style="width: 240px" placeholder="请选择到账比例" clearable size="small" >
            <el-option :label="`${item.identity}:${item.proportion}`"  :value="item.id" v-for="(item, index) in radioList" :key="index" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!loading">确 定</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm" v-else>提交中...</el-button>
        <el-button @click="cancel" plain>取 消</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {  listChannel, personJob, staff } from "@/api/recharge/personnel";
import { uploadFile } from "@/api/system/product";
import { allRadio } from "@/api/recharge/radio";
export default {
  name: "admin",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      dialogFormVisible:false,
      // 选中数组id
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      adminList: [],
      // 弹出层标题
      title: "异常信息",
      // 是否显示弹出层
      open: false,
      open1:false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        aliasName: undefined,
        startTime: undefined,
        endTime: undefined,
        identity: undefined,
        proportion: undefined,
        id:undefined,
        phone:undefined,
        card:undefined

      },
      // 表单参数
      form: {
        name:'',
        aliasName:''
      },
      // 到账比例
      radioList:[

      ],
      //批量到账比例处理
      staffList:[],
      // 表单校验
      rules: {
        id:[
           { required: true, message: "充值比例不能为空", trigger: "change"},
        ],
      },
      limit:100,
      num:0,
       // 文件显示
      fileList:[{"url":''}],
      errList:[],//异常信息
    };
  },
  created() {
    this.getList();
    this.getListczgl();
  },
  methods: {
    //上传文件
    handleChange(param){
      this.limit = 1
      this.num++
      if(this.num>1){
        this.num = 0
        return false
      }else{
        let  data = new FormData()// FormData 对象
        data.append('file', param.raw)
        uploadFile(data).then(res=>{
          if(res.status == "SUCCESS" && res.data.length>0){
            this.msgSuccess('充值文件上传成功，部分用户充值成功')
            this.errList = res.data
            this.open = true
          }else if(res.status == "SUCCESS" && res.data.length == "0"){
            this.msgSuccess('充值文件上传成功，文件用户均已充值完成')
          }else{

          }
          this.$refs.upload.submit();
        }).catch(err=>{
          this.$refs.upload.submit();
        })
      }
    },
    forceUpdate(){ //重置form
      this.form = JSON.parse(JSON.stringify(this.form));
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listChannel(this.addDateRange(this.queryParams)).then(response => {
          this.adminList = response.data.records;
          for(let i =0;i<this.adminList.length;i++){
            this.adminList[i].dept = JSON.parse(this.adminList[i].dept).name
          }
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    /** 获取充值管理的数据用于修改赋值 */
    getListczgl() {
      allRadio().then(response => {
        this.radioList = response.data.map(item=>{
          return {
            identity:item.identity,
            proportion:item.proportion,
            id:item.id
          }
        })
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open1 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ids: undefined,
        name: undefined,
        aliasName: undefined,
        adminType: "Y",
        proportion:undefined,
        id:undefined
      };
      this.staffList = []
      this.resetForm("form");
    },
    // 同步人员信息
    synchroPersonnel(){
      if(this.queryParams.name){
        personJob({"blurry":this.queryParams.name}).then(response =>{
          this.getList();
        })
        localStorage.setItem("timeout","大于10s")
        this.msgSuccess('请在定时任务中人员信息中，选择点击更多--调度日志查询同步进度 ', 5000)
        this.$router.push({path:'/system/job/jobTaskIndex'})
        localStorage.setItem('personnel', 1)
      }else{
        this.$message.error('同步人员信息不能为空')
      }


    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 微信支付宝充值跳转 */
    radio(row){
      this.$router.push({path:'userRecharge'})
      localStorage.setItem('chongzhi', JSON.stringify({"name":row.name,"proportion":row.proportion,"sid":row.sid,"contacts":row.contacts}))
    },
    /** 现金充值跳转 */
    cash(row){
      this.$router.push({path:'cash'})
      localStorage.setItem('chongzhi', JSON.stringify({"name":row.name,"proportion":row.proportion,"sid":row.sid,"contacts":row.contacts}))
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    //批量处理
    batchChange(change){
      if(this.ids.length>0){
        if(change == "1"){
            this.open1 = true;
            this.title = "修改参数";
        }else{
          this.loading = true;
          this.staffList = this.ids.map(item=>{
            return {
              staffId:item.sid,
              radioId:item.radioId,
              delFlag:0
            }
          })
          staff(this.staffList).then(response =>{
            this.loading = false;
            this.msgSuccess('批量解绑完成')
            this.getList();
            this.open1 = false;
          }).catch(err=>{
            this.loading = false;
            this.open1 = false;
          })
        }
      }else{
        this.$message.error('请勾选需要批量处理充值到账比例人员信息')
      }


    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["queryParams"].validate(valid => {
        if (valid) {
          if(this.queryParams.id){
            this.loading = true;
            this.staffList = this.ids.map(item=>{
              return {
                staffId:item.sid,
                radioId:this.queryParams.id,
                delFlag:1
              }
            })
            staff(this.staffList).then(response =>{
              this.loading = false;
              this.open1 = false;
              this.msgSuccess('批量绑定完成')
              this.getList();
              this.reset()
            }).catch(err=>{
              this.loading = false;
              this.open1 = false;
            })
          }
        }
      })
    },

    /** 导出按钮操作 */
    handleExport() {
        var a = document.createElement("a"); //创建一个<a></a>标签
        a.href = process.env.VUE_APP_FILE_API+'7695b261-d941-4bb6-b3d1-1e448edc6afb.xls'; // 给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
        a.download = "批量充值模板.xls"; //设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
        a.style.display = "none"; // 障眼法藏起来a标签
        document.body.appendChild(a); // 将a标签追加到文档对象中
        a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
        a.remove();
    },
  }
};
</script>
<style lang="scss" >
.el-select-dropdown__item.selected{
  font-weight: none !important;
}
</style>
