<template>
  <div class="userManage">
    <Form @keydown.enter.native="handleSearch" ref="searchForm" :model="searchForm" inline :label-width="70" class="search-form">
      <Form-item label="账号" prop="username">
        <Input
          type="text"
          v-model="searchForm.username"
          placeholder="请输入账号"
          clearable
        />
      </Form-item>
      <Form-item label="联系方式" prop="mobile">
        <Input
          type="text"
          v-model="searchForm.mobile"
          placeholder="请输入联系方式"
          clearable
        />
      </Form-item>
      <Form-item label="部门">
        <department-choose @on-change="(v)=> { this.searchForm.departmentId = v;}" ref="dep"></department-choose>
      </Form-item>
      <Form-item label="账户类型" prop="adminType">
        <Select
          v-model="searchForm.adminType"
          placeholder="请选择"
          clearable
        >
          <Option :value="1">商城管理员</Option>
          <Option :value="2">店铺管理员</Option>
        </Select>
      </Form-item>
      <div class="w_100 global_text_right">
        <Button
          @click="handleSearch"
          type="primary"
          >搜索</Button
        >
        <Button
          @click="handleClear"
          class="ml_20"
          >清空</Button
        >
      </div>
    </Form>
    <div class="flex-space-between mt_24 mb_24">
      <div>
        <Checkbox v-model="selectCount" @on-change="handleSelectAll">全选</Checkbox>
        <Button type="error" ghost :disabled="batchDisable" @click="delAll">批量删除</Button>
        <Button type="primary" class="ml_10"  ghost :disabled="batchDisable" @click="resetPass">重置密码</Button>
      </div>
      <div>
        <Button type="primary" @click="add">添加</Button>
      </div>
    </div>
    <Table
      :loading="loading"
      :columns="columns"
      :data="data"
      @on-selection-change="handleSelectionChange"
      ref="table"
    >
      <template slot="avatar" slot-scope="{ row }">
        <img v-if="!!row.avatar" :src="row.avatar" style="width:40px;height:40px;margin:10px 0"/>
        <img v-else src="https://yun.tuisnake.com/shopmanager/4c5c095c-eca1-409b-8388-5024a64ee436.png"  style="width:40px;height:40px;margin:10px 0"/>
      </template>
      <template slot="adminType" slot-scope="{ row }">
        <span>{{ row.adminType == 1 ? '商城管理员' : '店铺管理员' }}</span>
      </template>

      <template slot="storeManager" slot-scope="{ row }">
        <span>{{ row.storeManager && row.storeManager.length > 0 ? row.storeManager.map(item => {return item.storeName}).join(',') :'' }}</span>
      </template>
      <template slot="action" slot-scope="{ row }">
        <a @click="row.status ? disable(row) : enable(row)" type="text" class="mr_20"  :style="{color: row.status ? '#FF3B30' : ''}">{{ row.status ? '禁用' : '启用'}}</a>
        <a @click="edit(row)" type="text" class="mr_20">编辑</a>
        <a @click="remove(row)" style="color: #FF3B30" type="text">删除</a>
      </template>
    </Table>
    <Row type="flex" justify="end" class="mt_10">
      <Page
        :current="searchForm.pageNumber"
        :total="total"
        :page-size="searchForm.pageSize"
        @on-change="changePage"
        @on-page-size-change="changePageSize"
        :page-size-opts="[10,20,50]"
        size="small"
        show-total
        show-elevator
        show-sizer
      ></Page>
    </Row>
    <Drawer class="add-drawer" :title="modalTitle" placement="right" v-model="userModalVisible" width="600" @on-close="userModalVisible = false">
      <div class="collapse">
        <Form :label-width="120" ref="form" :model="form" class="add-form mt_20" :rules="formValidate">
          <FormItem  label="账号：" prop="username">
            <Input :disabled="modalType==1" v-model="form.username" autocomplete="off"/>
          </FormItem>
          <FormItem label="密码：" prop="password" :error="errorPass">
            <Input :disabled="modalType==1"  type="password" password v-model="form.password" autocomplete="off"/>
          </FormItem>
          <Form-item label="账号类型：" prop="adminType">
            <RadioGroup v-model="form.adminType">
              <Radio :label="1">商城管理员</Radio>
              <Radio :label="2">店铺管理员</Radio>
            </RadioGroup>
          </Form-item>
          <Form-item label="所属部门：" class="ivu-form-item-required" prop="departmentId">
            <department-choose :selectDepDef="form.departmentIdArr" @on-select-dep="(v) => {this.form.departmentIdArr = v}" @on-change="(v)=> { this.form.departmentId = v;}" ref="dep"></department-choose>
          </Form-item>
          <FormItem label="角色：" prop="roles">
            <CheckboxGroup v-model="form.roles">
              <Checkbox :label="item.id" v-for="item in roleList" :key="item.id">
                {{ item.name }}
              </Checkbox>
            </CheckboxGroup>
          </FormItem>
          <FormItem label="邮箱：" prop="email">
            <Input v-model="form.email"/>
          </FormItem>
          <FormItem label="手机号：" prop="mobile">
            <Input v-model="form.mobile"/>
          </FormItem>
          <FormItem label="昵称：" prop="nickName">
            <Input v-model="form.nickName" autocomplete="off"/>
          </FormItem>
          <Form-item label="是否启用：" prop="status">
            <RadioGroup v-model="form.status">
              <Radio :label="1">启用</Radio>
              <Radio :label="0">禁用</Radio>
            </RadioGroup>
          </Form-item>
          <Form-item label="头像：">
            <Upload
              style="display:inline-block;"
              :action="commonUrl + '/common/common/upload/file'"
              :headers="accessToken"
              :on-success="handleSuccess"
              :on-error="handleError"
              :show-upload-list="false"
              :max-size="1024*3"
              :on-exceeded-size="handleMaxSize"
              ref="up"
              :format="['jpg','jpeg','png','gif','bmp']"
              accept=".jpg, .jpeg, .png, .gif, .bmp"
              :on-format-error="handleFormatError"
            >
            <div class="img-upload" :class="form.avatar ? 'img-upload-fill' : ''">
              <template v-if="!!form.avatar">
                <img :src="form.avatar"/>
                <Icon @click="handleDeleteUploadImg" class="primary-close primary-icon" type="ios-close-circle"/>
              </template>
              <template v-else>
                <iconpark-icon width="28px" height="28px" name="common-add-img"></iconpark-icon>
                上传图片
              </template>
            </div>
            </Upload>
          </Form-item>
        </Form>
      </div>
      <div class="collapse-foot border_t">
        <Button type="text" @click="userModalVisible = false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submitUser">确定</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
import {
  getUserListData,
  getAllRoleList,
  addUser,
  editOtherUser,
  enableUser,
  deleteUser,
  resetPassword
} from "@/api/index";
import {validateMobile} from "@/libs/validate";
import departmentChoose from "@/components/lili/department-choose";
import departmentTreeChoose from "@/components/lili/department-tree-choose";
import uploadPicInput from "@/components/lili/upload-pic-input";
import { commonUrl } from "@/libs/axios";
import { initDepartment } from "@/api/index";
export default {
  name: "user-manage",
  components: {
    departmentChoose,
    departmentTreeChoose,
    uploadPicInput,
  },
  data() {
    return {
      // 上传
      commonUrl, // 上传文件路径
      accessToken: {}, // 上传token鉴权
      loading: true, // 加载状态
      selectCount: 0, // 已选数量
      selectList: [], // 已选数据列表
      searchForm: { // 请求参数
        username: "",
        departmentId: "",
        mobile: "",
        pageNumber: 1,
        pageSize: 10,
        sort: "createTime",
        order: "desc",
        adminType: null
      },
      modalType: 0, // 新增编辑标识
      userModalVisible: false, // 用户modal显隐
      modalTitle: "", // modal标题
      form: { // 表单
        username: "",
        mobile: "",
        email: "",
        roles: [],
        departmentId: '',
        avatar: '',
        adminType: 1,
        status: 1,
        nickName: '',
        password: '',
        departmentIdArr: []
      },
      roleList: [], // 角色列表
      errorPass: "", // 错误提示
      formValidate: { // 验证规则
        username: [
          {required: true, message: "账号不能为空", trigger: "blur"}
        ],
        nickName:  [
          {required: true, message: "昵称不能为空", trigger: "blur"}
        ],
        password: [
          {required: true, message: "密码不能为空", trigger: "blur"}
        ],
        mobile: [
          {required: true, message: "手机号不能为空", trigger: "blur"},
          {validator: validateMobile, trigger: "blur"}
        ],
        email: [
          {required: true, message: "请输入邮箱地址"},
          {type: "email", message: "邮箱格式不正确"}
        ],
        adminType: [
          {required: true, message: "请选择账户类型"},
        ],
        roles: [
          {required: true, message: "请选择账户角色"},
        ],
        status: [
          {required: true, message: "请选择是否启用"},
        ],
        departmentId: [
          {validator:(rules,values,cb)=> {
            if(this.form.departmentId.length == 0) {
              cb(new Error('所属部门不能为空'))
              return
            }  else {
              cb()
            }
          }, trigger: "blur"}
        ]
      },
      submitLoading: false, // 提交状态
      columns: [ // 表头
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: "账号",
          key: "username",
          minWidth: 120,
          sortable: true,
        },
        {
          title: "头像",
          key: "avatar",
          width: 80,
          slot: "avatar",
        },
        {
          title: "手机",
          key: "mobile",
          width: 125
        },
        {
          title: "邮箱",
          key: "email",
          minWidth: 180,
          sortable: true
        },
        {
          title: "状态",
          key: "status",
          width: 110,
          render: (h, params) => {
            if (params.row.status == true) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "启用"
                  }
                })
              ]);
            } else if (params.row.status == false) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "error",
                    text: "禁用"
                  }
                })
              ]);
            }
          },
          filters: [
            {
              label: "启用",
              value: true
            },
            {
              label: "禁用",
              value: false
            }
          ],
          filterMultiple: false,
          filterMethod(value, row) {
            return row.status == value;
          }
        },
        {
          title: "创建时间",
          key: "createTime",
          sortable: true,
          sortType: "desc",
          width: 180
        },
        {
          title: "账号类型",
          key: "adminType",
          width: 180,
          slot: "adminType"
        },
        {
          title: "店铺",
          key: "storeManager",
          width: 180,
          slot: "storeManager"
        },
        {
          title: "操作",
          key: "action",
          width: 200,
          fixed: 'right',
          slot: "action"
        }
      ],
      data: [], // 用户数据
      total: 0, // 总数
    };
  },
  computed: {
    batchDisable() {
      if(this.selectCount) {
        return false
      }
      if(this.selectList.length > 0) {
        return false
      }
      return true
    }
  },
  methods: {
    // 全选
    handleSelectAll(isAll) {
      this.$refs.table.selectAll(isAll);
    },
    // 选择部分内容
    handleSelectionChange(list) {
      this.exportData = list;
      this.selectList = list;
      this.selectCount = list.length;
    },
    // 清除选中状态
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    // 初始化数据
    init() {
      this.accessToken = {
        accessToken: this.getStore("accessToken"),
      };
      this.getUserList();
    },
    // 分页 修改页码
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getUserList();
      this.clearSelectAll();
    },
    // 分页 修改页数
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.searchForm.pageNumber = 1;
      this.getUserList();
    },
    getUserList() {
      // 多条件搜索用户列表
      this.loading = true;
      getUserListData(this.searchForm).then(res => {
        this.loading = false;
        if (res.success) {
          this.data = res.result.records;
          this.total = res.result.total;
        }
      });
    },
    // 搜索
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getUserList();
    },
    handleClear() {
      this.$refs['dep'].clearSelect();
      this.searchForm.departmentId = '';
      this.$refs['searchForm'].resetFields();
      this.getUserList()
    },
    // 获取角色列表
    getRoleList() {
      let params = {
        pageSize: 100
      }
      getAllRoleList(params).then(res => {
        if (res.success) {
          this.roleList = res.result.records;
        }
      });
    },
    // 批量删除
    delAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning("您还未选择要删除的数据");
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
        loading: true,
        onOk: () => {
          let ids = "";
          this.selectList.forEach(function (e) {
            ids += e.id + ",";
          });
          ids = ids.substring(0, ids.length - 1);
          deleteUser(ids).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("删除成功");
              this.clearSelectAll();
              this.getUserList();
            }
          });
        }
      });
    },
    // 重置密码
    resetPass() {
      if(this.selectCount==0) {this.$Message.warning('请选中数据后重试!'); return}
      this.$Modal.confirm({
        title: "确认重置",
        content:
          "您确认要重置所选的 " +
          this.selectCount +
          " 条用户数据密码为【123456】?",
        loading: true,
        onOk: () => {
          let ids = "";
          this.selectList.forEach(function (e) {
            ids += e.id + ",";
          });
          ids = ids.substring(0, ids.length - 1);
          resetPassword(ids).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.clearSelectAll();
              this.getUserList();
            }
          });
        }
      });
    },

    // 格式校验
    handleFormatError(file) {
      this.$Message.error('所选文件格式不正确, 请选择 .jpg .jpeg .png .gif .bmp格式文件');
    },
    // 上传文件超过大小限制
    handleMaxSize(file) {
      this.$Message.error('所选文件大小过大, 不得超过 3M.');
    },
    // 上传成功回调
    handleSuccess(res, file) {
      if (res.success) {
        this.$Message.success("上传文件 " + file.name + " 成功");
        this.form.avatar = res.result
      } else {
        this.$Message.error(res.message);
      }
    },
    // 上传失败回调
    handleError(error, file, fileList) {
      this.$Message.error(error.toString());
    },
    // 删除已经上传的图片
    handleDeleteUploadImg(event) {
      event.stopPropagation();
      this.form.avatar = ''
    },
    // 确认提交
    submitUser() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 添加用户 避免编辑后传入id
          const params = JSON.parse(JSON.stringify(this.form))
          if (params.password == "" || params.password == undefined) {
            this.errorPass = "密码不能为空";
            return;
          }
          if (params.password.length < 6) {
            this.errorPass = "密码长度不得少于6位";
            return;
          }
          params.password = this.md5(params.password)
          params.roles = params.roles.join(',')
          if(this.form.status == 1) {
            this.form.status = true
          } else {
            this.form.status = false
          }

          this.submitLoading = true;
          if (this.modalType == 0) {
            addUser(params).then(res => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.getUserList();
                this.userModalVisible = false;
              }
            });
          } else {
            delete params.password
            editOtherUser(params).then(res => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.getUserList();
                this.userModalVisible = false;
              }
            });
          }
        }
      });
    },
    // 添加用户
    add() {
      this.modalType = 0;
      this.modalTitle = "添加用户";
      this.$refs.form.resetFields();
      this.form = { // 表单
        username: "",
        mobile: "",
        email: "",
        roles: [],
        departmentId: '',
        avatar: '',
        adminType: 1,
        status: 1,
        nickName: '',
        password: '',
        departmentIdArr: []
      };
      this.$refs['dep'].clearSelect();
      this.userModalVisible = true;
    },
    // 编辑用户
    async edit(v) {
      this.$refs.form.resetFields();
      this.form = JSON.parse(JSON.stringify(v));
      this.modalType = 1;
      this.modalTitle = "编辑用户";
      for (let avatar in this.form) {
        if (this.form[avatar] == null) {
          this.form[avatar] = "";
        }
      }
      if(this.form.status) {
        this.form.status = 1
      } else {
        this.form.status = 0
      }
      let selectRolesId = this.form.roleIds.split(',');
      this.form.roles = selectRolesId;
      let departmentIdArr =  this.form.departmentIdArr.split(',');
      this.form.departmentIdArr = departmentIdArr
      this.userModalVisible = true;
    },
    // 启用
    enable(v) {
      let params = {
        status: true
      }
      this.$Modal.confirm({
        title: "确认启用",
        content: "您确认要启用用户 " + v.username + " ?",
        loading: true,
        onOk: () => {
          enableUser(v.id, params).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.getUserList();
            }
          });
        }
      });
    },
    // 禁用
    disable(v) {
      let params = {
        status: false
      }
      this.$Modal.confirm({
        title: "确认禁用",
        content: "您确认要禁用用户 " + v.username + " ?",
        loading: true,
        onOk: () => {
          enableUser(v.id, params).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.getUserList();
            }
          });
        }
      });
    },
    // 删除用户
    remove(v) {
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除用户 " + v.username + " ?",
        loading: true,
        onOk: () => {
          deleteUser(v.id).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("删除成功");
              this.getUserList();
            }
          });
        }
      });
    },


  },
  mounted() {
    this.init();
    this.getRoleList();
  }
};
</script>
