<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.userapp_delete"
                   @click="handleDelete">删 除
        </el-button>

      </template>
      <template slot-scope="{type,size,row}" slot="menu">
         <el-button icon="el-icon-connection" :size="size" :type="type" @click="untieUser(row)">解冻</el-button>
      </template>
    </avue-crud>


    <el-dialog title="导出" append-to-body :visible.sync="userExportShow" width="30%">
      <el-form :model="userExportForm" ref="addUserTicketForm" label-width="80px">
        <el-form-item label="日  期" prop="score">
          <el-date-picker v-model="userExportForm.exportTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userExportShow = false" :loading="userExportLoading">取 消</el-button>
        <el-button type="primary" @click="userExportConfirm" :loading="userExportLoading">确 定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<style>
.codeGeting{
  background: #cdcdcd;
  border-color: #cdcdcd;
}
</style>

<script>
  import {getList, getDetail, add, update, remove, untie, sendValidCode, addUserScore, expExcelConsign} from "../..//api/platform/userapp";
  import {mapGetters} from "vuex";
  import {addRedIntegral} from "../../api/platform/userapp";

  export default {
    data() {
      return {
        addTicketButLoading: false,
        getCodeButName: '获取验证码',
        disable: false,
        isGeting: false,
        count: 60,
        addUserTicketBox: false,
        addRedIntegralBox: false,
        addUserTicketForm: {
          score: '',
          code: '',
          codeId: ''
        },
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          // index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "主键ID",
              prop: "id",
              hide: true,
              display: false,
            },
            {
              label: "用户ID",
              prop: "userId",
              hide: true,
              display: false,
            },
            {
              label: "姓名",
              // prop: "name",
              prop: "realName",
              addDisplay: false,
              editDisplay: false,
              search: true,
            },
            {
              label: "账号",
              prop: "username",
              addDisplay: false,
              editDisplay: false,
              search: true,
            },
            {
              label: "手机号",
              prop: "phone",
              addDisplay: false,
              editDisplay: false,
              search: true,
            },
            // {
            //   label: "邀请码",
            //   prop: "code",
            //   hide: true,
            //   addDisplay: false,
            //   editDisplay: false,
            // },
            // {
            //   label: "活跃度",
            //   prop: "userActive",
            //   addDisplay: false,
            //   editDisplay: false,
            // },
            // {
            //   label: "绿色积分",
            //   prop: "ticket",
            //   addDisplay: false,
            //   editDisplay: false,
            // },
            // {
            //   label: "信誉分",
            //   prop: "creditScore",
            //   addDisplay: false,
            //   editDisplay: false,
            // },
            // {
            //   label: "特殊权限",
            //   prop: "enableAuthDisplayName",
            //   addDisplay: false,
            //   editDisplay: false,
            // },
            // {
            //   label: "特殊权限",
            //   prop: "enableAuth",
            //   type: "select",
            //   dicUrl: "/api/blade-system/dict/dictionary?code=yes_no",
            //   props: {
            //     label: "dictValue",
            //     value: "dictKey"
            //   },
            //   dataType: "number",
            //   hide: true,
            //   search: true,
            //   addDisplay: false,
            //   rules: [{
            //     required: true,
            //     message: "请选择特殊权限",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "生活馆账号",
            //   prop: "livingHallDisplayName",
            //   addDisplay: false,
            //   editDisplay: false,
            // },
            // {
            //   label: "生活馆账号",
            //   prop: "livingHall",
            //   type: "select",
            //   dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
            //   props: {
            //     label: "dictValue",
            //     value: "dictKey"
            //   },
            //   dataType: "number",
            //   hide: true,
            //   addDisplay: false,
            //   rules: [{
            //     required: true,
            //     message: "请选择生活馆账号",
            //     trigger: "blur"
            //   }]
            // },
            {
              label: "状态",
              prop: "stateDisplayName",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "状态",
              prop: "state",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=user_state",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              hide: true,
              search: true,
              addDisplay: false,
              rules: [{
                required: true,
                message: "请选择状态",
                trigger: "blur"
              }]
            }, {
              label: "注册时间",
              prop: "createTime",
              addDisplay: false,
              editDisplay: false,
            },
          ]
        },
        data: [],
        userExportShow: false,
        userExportForm: {},
        userExportLoading: false
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.userapp_add, false),
          viewBtn: this.vaildData(this.permission.userapp_view, false),
          delBtn: this.vaildData(this.permission.userapp_delete, false),
          editBtn: this.vaildData(this.permission.userapp_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      userExportConfirm() {
        // alert('导出')
        if(this.selectionList.length < 1) {
          this.$message.error('请先勾选寄售账单');
          return;
        }
        this.userExportLoading = true;
        let accounts = this.selectionList.map(ele => ele.username);
        let createStartTime = '';
        let createEndTime = '';
        if(this.userExportForm.exportTime && this.userExportForm.exportTime[0]) createStartTime = this.userExportForm.exportTime[0];
        if(this.userExportForm.exportTime && this.userExportForm.exportTime[1]) createEndTime = this.userExportForm.exportTime[1];
        expExcelConsign({ accounts, createStartTime, createEndTime}).then(res => {
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let a = document.createElement('a');
          a.style.display = 'none';
          a.href = url;
          // 下面两行是自己项目需要的处理，总之就是得到下载的文件名（加后缀）即可
          var fileName = '寄售订单数据.xlsx';
          a.setAttribute('download',fileName);
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
          this.userExportLoading = false;
          this.userExportShow = false;
          this.$message.success("文件下载成功");
        })
        .catch(err => {
          this.userExportLoading = false;
          this.$message.error(err.msg || err.message || '操作失败');
        });
      },
      untieUser(row) {
        this.$confirm('此操作将会解冻该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
          untie(row.userId).then(res => {
            if(res.data.code != 200) this.$message.error(res.data.msg);
            else this.$message.success(res.data.msg);
            this.loading = false;
          })
        }).catch(() => {});
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleAddTicket() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择一条数据");
          return;
        }
        if (this.selectionList.length > 1) {
          this.$message.warning("只能选择一条数据");
          return;
        }
        this.addUserTicketBox = true;

      },
      handleAddRedIntegral() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择一条数据");
          return;
        }
        if (this.selectionList.length > 1) {
          this.$message.warning("只能选择一条数据");
          return;
        }
        this.addRedIntegralBox = true;
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      handleSendValidCode() {
        sendValidCode().then(res => {
          const data = res.data;
          if (data.code !== 200) {
            this.$message.warning("短信发送失败");
            return;
          }
          this.addUserTicketForm.codeId = data.data.id;
          const countDown = setInterval(() => {
            if (this.count < 1) {
              this.isGeting = false
              this.disable = false
              this.getCodeButName = '获取验证码'
              this.count = 6
              clearInterval(countDown)
            } else {
              this.isGeting = true
              this.disable = true
              this.getCodeButName = this.count-- + 's后重发'
            }
          }, 1000)
        })
      },
      submitTicket() {
        this.$refs["addUserTicketForm"].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '处理中，请稍等...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            this.addTicketButLoading = true;
            this.addUserTicketForm.userId = this.selectionList[0].userId;
            addUserScore(this.addUserTicketForm).then(res => {
              this.addTicketButLoading = false;
              loading.close();
              const data = res.data;
              if (data.code !== 200) {
                this.$message.warning(data.msg);
                return;
              }
              this.$message.success("增加成功");
              this.addUserTicketBox = false
              this.addUserTicketForm = {};
              this.onLoad(this.page, this.query);
            })
          } else {
            return false;
          }
        });
      },
      submitTicketRed() {
        this.$refs["addUserTicketForm"].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '处理中，请稍等...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            this.addTicketButLoading = true;
            this.addUserTicketForm.userId = this.selectionList[0].userId;
            addRedIntegral(this.addUserTicketForm).then(res => {
              this.addTicketButLoading = false;
              loading.close();
              const data = res.data;
              if (data.code !== 200) {
                this.$message.warning(data.msg);
                return;
              }
              this.$message.success("增加成功");
              this.addRedIntegralBox = false
              this.addUserTicketForm = {};
              this.onLoad(this.page, this.query);
            })
          } else {
            return false;
          }
        });
      }
    }
  };
</script>

<style>
</style>
