<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="isStore" slot-scope="scope">
        <el-tag v-if="scope.row.isStore === 1" type="success">{{ scope.row.$isStore }}</el-tag>
        <el-tag v-if="scope.row.isStore === 0" type="primary">{{ scope.row.$isStore }}</el-tag>
      </template>

      <template slot="livingHall" slot-scope="scope">
        <el-tag v-if="scope.row.livingHall === 0" type="warning">{{ scope.row.$livingHall }}</el-tag>
        <el-tag v-else-if="scope.row.livingHall === 1" type="success">{{ scope.row.$livingHall }}</el-tag>
      </template>

      <template slot-scope="{type,size,row}" slot="menu">
         <el-button v-if="row.state == 1" :size="size" :type="type" @click="forbidden(row, 2)">禁用</el-button>
         <el-button v-if="row.state == 2" :size="size" :type="type" @click="forbidden(row, 1)">启用</el-button>
         <el-button v-if="row.livingHall === 0" :size="size" :type="type" @click="setLeader(row)">设为团长</el-button>
         <el-button v-if="row.livingHall === 1" :size="size" :type="type" @click="removeLeader(row)">移除团长</el-button>
      </template>
    </avue-crud>

    <el-dialog title="选择自提点" :visible.sync="dialogVisible" width="80%" :append-to-body="true" :before-close="handleClose" >
      <avue-crud :option="selfTakeOption"
                 :table-loading="selfTakeLoading"
                 :data="selfTakeData"
                 :page.sync="selfTakePage"
                 v-model="selfTakeForm"
                 ref="selfTakeCrud"
                 @search-change="selfTakeSearchChange"
                 @search-reset="selfTakeSearchReset"
                 @selection-change="selfTakeSelectionChange"
                 @current-change="selfTakeCurrentChange"
                 @size-change="selfTakeSizeChange"
                 @refresh-change="selfTakeRefreshChange"
                 @on-load="selfTakeOnLoad">
      </avue-crud>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addUserSelfTake">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="新增供应商" append-to-body :visible.sync="addUserTicketBox" width="450px" :before-close="handleClose">
      <el-form :model="store" ref="store" label-width="80px">
        <el-form-item label="会员名称" labelWidth="130" prop="userName">
          <el-input v-model="store.userName" disabled="false" />
        </el-form-item>
        <el-form-item label="供应商名称" labelWidth="130"  prop="name" :rules="[{ required: true, message: '供应商名称不能为空'}]">
          <el-input v-model="store.name" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="供应商电话" labelWidth="130"  prop="tel" :rules="[{ required: true, message: '电话不能为空'}]">
          <el-input v-model="store.tel" placeholder="请输入供应商名称电话" />
        </el-form-item>
        <el-form-item label="供应商地址" labelWidth="130"  prop="tel" :rules="[{ required: true, message: '电话不能为空'}]">
          <el-input v-model="store.storeAddress" placeholder="请输入供应商地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserTicketBox = false">取 消</el-button>
        <el-button type="primary" @click="submitTicket" :loading="addTicketButLoading">确 定</el-button>
      </div>
    </el-dialog>

  </basic-container>
</template>

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

<script>
  import {getList, getDetail, add, update, remove, addStore, removeCommander, setUpCommander} from "../../api/platform/userapp";
  import {listByUserId,getList as getSelfTakeList,addUserSelfTake } from "../../api/groupon/selftake";
  import {mapGetters} from "vuex";
  import {selfTakeOption} from "../../option/platform/userapp"

  export default {
    data() {
      return {
        leaderUserId: 0,
        selfTakeOption: selfTakeOption,
        addTicketButLoading: false,
        dialogVisible: false,
        getCodeButName: '获取验证码',
        disable: false,
        isGeting: false,
        count: 60,
        addUserTicketBox: false,
        addUserTicketForm: {
          score: '',
          code: '',
          codeId: ''
        },
        store: {
          userId: '',
          userName: '',
          name: '',
          storeAddress: '',
          tel: ''
        },
        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,
          viewBtnIcon: ' ',
          editBtnIcon: ' ',
          selection: false,
          dialogClickModal: false,
          menuAlign: 'left',
          searchLabelWidth:100,
          menuWidth: 200,
          searchIcon: true,
          searchIndex: 3,
          column: [
            {
              label: "主键ID",
              prop: "id",
              hide: true,
              display: false,
            },
            {
              label: "用户ID",
              prop: "userId",
              hide: true,
              display: false,
            },
            {
              label: "会员昵称",
              prop: "name",
              addDisplay: true,
              editDisplay: true,
              search: true,
            },
            {
              label: "会员姓名",
              prop: "realName",
              addDisplay: true,
              editDisplay: true,
              search: true,
            },
            {
              label: "手机号",
              prop: "phone",
              addDisplay: false,
              editDisplay: false,
              search: true,
            },
            // {
            //   label: "供应商身份",
            //   prop: "isStore",
            //   type: "select",
            //   dicUrl: "/api/blade-system/dict-biz/dictionary?code=is_store",
            //   props: {
            //     label: "dictValue",
            //     value: "dictKey"
            //   },
            //   dataType: "number",
            //   hide: false,
            //   search: true,
            //   addDisplay: false,
            //   editDisplay: false,
            //   rules: [{
            //     required: true,
            //     message: "请选择状态",
            //     trigger: "blur"
            //   }]
            // },
            {
              label: "团长身份",
              prop: "livingHall",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=is_captain",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              hide: false,
              search: true,
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "请选择状态",
                trigger: "blur"
              }]
            },
            {
              label: "状态",
              prop: "state",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=user_state",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              hide: false,
              search: true,
              addDisplay: true,
              rules: [{
                required: true,
                message: "请选择状态",
                trigger: "blur"
              }]
            },
            {
              label: "注册时间",
              prop: "createTime",
              addDisplay: false,
              editDisplay: false,
              width: 150
            },
          ]
        },
        data: [],
        userExportShow: false,
        userExportForm: {},
        userExportLoading: false,
        selfTakeList:[],
        selfTakeListTotal:0,
        mySelfTakeList:[],
        mySelfTakeListTotal:0,
        row:{},

        selfTakePage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selfTakeData: [],
        selfTakeLoading: false,
        selfTakeForm: {},
        selfTakeQuery: {},
        selfTakeSelectionList: []
      };
    },
    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: {

      deleteRow(index,mySelfTakeList){
        console.log(index);
        console.log(mySelfTakeList);
        this.mySelfTakeList =[];
      },

      addUserSelfTake(){
        if (this.selfTakeSelectionList.length === 0) {
          this.$message.warning("请选择一条数据");
          return;
        }
        if (this.selfTakeSelectionList.length > 1) {
          this.$message.warning("只能选择一条数据");
          return;
        }
        setUpCommander({
          userId: this.leaderUserId,
          selfTakeId: this.selfTakeSelectionList[0].id
        }).then(res =>{
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.onLoad(this.page, this.query)
          this.handleClose();
        })
      },

      handleCurrentChange(e){
        let arr = [];
        arr.push(e);
        this.mySelfTakeList = arr;
      },
      getCurrentChange(e){
        console.log(e)
        getSelfTakeList(e,10,{status:1}).then(res =>{
          console.log(res)
          this.selfTakeListTotal = res.data.data.total
          this.selfTakeList = res.data.data.records
        })

      },

      addSelftake(row){
        this.row =row;
        this.dialogVisible = true;
        getSelfTakeList(1,10,{status:1}).then(res =>{
          console.log(res)
          this.selfTakeListTotal = res.data.data.total
          this.selfTakeList = res.data.data.records
        })
        listByUserId(row.userId).then(res =>{
          this.mySelfTakeList = res.data.data

        })
      },

      /**
       * 移除团长
       * @param row
       */
      removeLeader(row) {
        removeCommander({
          userId: row.userId
        }).then(res =>{
          this.onLoad(this.page, this.query);
          this.$message({
            type: "success",
            message: "移除成功"
          });
        })
      },

      setLeader(row) {
        this.leaderUserId = row.userId;
        this.dialogVisible = true;
      },

      /**
       * 禁用用户
       * @param row
       * @param state
       */
      forbidden(row, state) {
        let title = state == 1 ? '启用' : '禁用';
        this.$confirm('此操作将会' + title+ '该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          row.state = state;
          this.loading = true;
          update(row).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(row) {
        this.store.userName = row.realName
        this.store.userId = row.userId
        this.store.tel = row.phone
        this.addUserTicketBox = 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;
        this.query.userType = 2;
        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();
        });
      },

      submitTicket() {
        this.$refs["store"].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;
            addStore(this.store).then(res => {
              loading.close();
              this.$message.success("增加成功");
              this.onLoad(this.page, this.query);
              this.handleClose()
            }).catch(e => {
              this.addTicketButLoading = false;
              loading.close();
            })
          } else {
            return false;
          }
        });
      },

      selfTakeSearchReset() {
        this.selfTakeQuery = {};
        this.selfTakeOnLoad(this.selfTakePage);
      },
      selfTakeSearchChange(params, done) {
        this.selfTakeQuery = params;
        this.selfTakePage.currentPage = 1;
        this.selfTakeOnLoad(this.selfTakePage, params);
        done();
      },
      selfTakeSelectionChange(list) {
        this.selfTakeSelectionList = list;
      },
      selfTakeSelectionClear() {
        this.selfTakeSelectionList = [];
        this.$refs.selfTakeCrud.toggleSelection();
      },
      selfTakeCurrentChange(currentPage){
        this.selfTakePage.currentPage = currentPage;
      },
      selfTakeSizeChange(pageSize){
        this.selfTakePage.pageSize = pageSize;
      },
      selfTakeRefreshChange() {
        this.selfTakeOnLoad(this.selfTakePage, this.selfTakeQuery);
      },
      selfTakeOnLoad(page, params = {}) {
        this.selfTakeLoading = true;
        this.selfTakeQuery.status = 1;
        this.selfTakeQuery.isAdmin = 1;
        getSelfTakeList(page.currentPage, page.pageSize, Object.assign(params, this.selfTakeQuery)).then(res => {
          const data = res.data.data;
          this.selfTakePage.total = data.total;
          this.selfTakeData = data.records;
          this.selfTakeLoading = false;
          this.selfTakeSelectionClear();
        });
      },

      handleClose() {
        this.selfTakeSelectionClear();
        this.leaderUserId = 0;
        this.dialogVisible = false;
        this.addUserTicketBox = false
        this.store = {};
        this.addTicketButLoading = false;
      },

      /**
       * 移除供应商
       */
      removeStore(row) {

      }
    }
  };
</script>

<style>
</style>
