<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="部门">
        <department-choose
          @on-change="
            (v) => {
              this.searchForm.departmentId = v;
            }
          "
          ref="dep"
        ></department-choose>
      </Form-item>
      <Form-item label="角色" prop="roleId">
        <Select v-model="searchForm.roleId" clearable>
          <Option v-for="item in roleList" :value="item.id" :key="item.id">{{
            item.name
          }}</Option>
        </Select>
      </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_12"
          ghost
          :disabled="batchDisable"
          @click="resetPass"
          >重置密码</Button
        >
      </div>
      <div class="mt_12">
        <Button type="primary" @click="add">添加</Button>
      </div>
    </div>
    <Table
      :loading="loading"
      :columns="columns"
      :data="data"
      @on-selection-change="handleSelectionChange"
      ref="table"
    >
      <template slot="roles" slot-scope="{ row }">
        <div v-if="row.roles && row.roles.length > 0">
          <span v-for="item in row.roles">
            {{ item.name }}
          </span>
        </div>
      </template>
      <template slot="adminType" slot-scope="{ row }">
        <span>{{ row.adminType == 1 ? "平台管理员" : "个人管理员" }}</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="800"
      @on-close="userModalVisible = false"
    >
      <div class="collapse">
        <Form
          :label-width="160"
          ref="form"
          :model="form"
          class="add-form mt_20"
          :rules="formValidate"
        >
          <FormItem label="账号：" prop="username">
            <Input
              v-model="form.username"
              autocomplete="off"
              placeholder="请输入账号"
            />
          </FormItem>
          <FormItem label="密码：" prop="password" :error="errorPass">
            <Input
              type="password"
              password
              v-model="form.password"
              autocomplete="off"
              placeholder="请输入密码"
            />
          </FormItem>
          <FormItem label="tuia-ssp账户ID：" prop="ssoIdArr">
            <Input
              v-model="form.ssoIdArr"
              autocomplete="off"
              placeholder="多个id，请用英文逗号隔开"
            />
          </FormItem>

          <FormItem label="快手ID：" prop="thirdPartyIdArr">
            <Input
              v-model="form.thirdPartyIdArr"
              autocomplete="off"
              placeholder="多个id，请用英文逗号隔开"
            />
          </FormItem>
          <Form-item label="账号类型：" prop="adminType">
            <RadioGroup v-model="form.adminType">
              <Tooltip
                content="仅可以管理自己的广告账户等"
                placement="top-start"
              >
                <Radio :label="1"
                  >平台管理员<Icon type="ios-help-circle-outline"
                /></Radio>
              </Tooltip>

              <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";
export default {
  name: "user-manage",
  components: {
    departmentChoose,
    departmentTreeChoose,
    uploadPicInput,
  },
  data() {
    return {
      // 上传
      commonUrl, // 上传文件路径
      accessToken: {}, // 上传token鉴权
      loading: true, // 加载状态
      selectCount: 0, // 已选数量
      selectList: [], // 已选数据列表
      searchForm: {
        // 请求参数
        username: "",
        departmentId: "",
        pageNumber: 1,
        pageSize: 10,
        sort: "gmt_create",
        order: "desc",
        adminType: null,
        roleId: "",
      },
      modalType: 0, // 新增编辑标识
      userModalVisible: false, // 用户modal显隐
      modalTitle: "", // modal标题
      form: {
        // 表单
        username: "",
        mobile: "",
        email: "",
        roles: [],
        departmentId: "",
        avatar: "",
        adminType: 1,
        ssoIdArr: "",
        thirdPartyIdArr: "",
        status: 0,
        nickName: "",
        password: "",
        departmentIdArr: [],
      },
      roleList: [], // 角色列表
      errorPass: "", // 错误提示
      formValidate: {
        // 验证规则
        username: [
          { required: true, message: "账号不能为空", trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        ssoIdArr: [
          {
            required: true,
            message: "tuia-ssp账户ID不能为空",
            trigger: "blur",
          },
        ],
        thirdPartyIdArr: [
          { required: true, message: "快手ID不能为空", 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",
          width: 120,
          sortable: true,
        },
        {
          title: "部门",
          key: "departmentTitle",
          width: 120,
        },
        {
          title: "角色",
          key: "roles",
          minWidth: 120,
          slot: "roles",
        },
        {
          title: "tuia-ssp账户ID",
          key: "ssoIdArr",
          minWidth: 120,
        },
        {
          title: "快手ID",
          key: "thirdPartyIdArr",
          minWidth: 120,
        },
        {
          title: "账户类型",
          key: "adminType",
          width: 120,
          slot: "adminType",
        },
        {
          title: "状态",
          key: "status",
          width: 120,
          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: "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;
      console.log(typeof this.searchForm.departmentId);
      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() {
      console.log("this.form", this.form);
      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;
          }
          console.log("params", params);
          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>
