<template>
  <div class="app-container">

    <card-table :modalData="userList" labelWidth="120px" :searchParams="queryParams" @pagination="getList"
                @selection-change="handleSelectionChange" :loading="loading" :tableSearch="true"
                @columnSearch="handleQuery" @resetList="resetQuery"
                :delProp="['createTime']">
      <template #operations="{ selections }">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:user:add']"
          >{{ $t('user.newUser') }}
          </el-button>
        </el-col>
      </template>

      <template #default="{ list }">
        <el-table-column type="selection" width="50" align="center"/>
        <Column :label="$t('user.account')" prop="userName" :searchParams="queryParams" :showSearch="true"/>
        <Column :label="$t('user.nick')" prop="nickName" :searchParams="queryParams" :showSearch="true"/>
        <Column :label="$t('user.role')" prop="roleId" :searchParams="queryParams" :showSearch="true"
                searchType="select" :searchDict="allRoleOptions" valueProp="roleId" labelProp="roleName">
          <template #default="{ row }">
            <span>{{ row.roleNames }}</span>
          </template>
        </Column>
        <Column :label="$t('user.agent')" prop="agentName" :searchParams="queryParams" :showSearch="true"/>
        <Column :label="$t('user.area')" prop="areaId" :searchParams="queryParams" :showSearch="true"
                searchType="select" :searchDict="areaOptions" valueProp="areaId" labelProp="areaName">
          <template #default="{ row }">
            <span>{{ row.areaName }}</span>
          </template>
        </Column>
        <Column :label="$t('user.country')" prop="countryName" :searchParams="queryParams" :showSearch="true"/>
        <Column :label="$t('user.email')" prop="email"/>
        <Column :label="$t('user.phoneNo')" prop="phonenumber"/>
        <Column :label="$t('user.status')" prop="status" :searchParams="queryParams" :showSearch="true"
                searchType="select" :searchDict="dict.type.sys_normal_disable">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(row)"
            ></el-switch>
          </template>
        </Column>

        <Column :label="$t('common.createTime')" prop="createTime" :searchParams="queryParams" :showSearch="true"
                searchType="dateRange" width="250px">
          <!--<template #default="{ row }">-->
          <!--  <span>{{ parseTime(row.createTime) }}</span>-->
          <!--</template>-->
        </Column>
        <Column :label="$t('common.operate')" :min-width="300" fixed="right" :showSearch="true" searchType="operate">
          <template #default="{ row }">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(row)"
              v-hasPermi="['system:user:edit']"
            >{{ $t('common.edit') }}
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(row)"
              v-hasPermi="['system:user:remove']"
            >{{ $t('common.delete') }}
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh-left"
              @click="handleResetPwd(row)"
              v-hasPermi="['system:user:resetPwd']"
            >{{ $t('user.resetPasswd') }}
            </el-button>
          </template>
        </Column>

      </template>
    </card-table>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" v-if="open">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('user.nick')" prop="nickName">
              <el-input v-model.trim="form.nickName" :placeholder="$t('user.placeholder_nick')" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('user.agent')" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" :noResultsText="$t('common.noResultsText')"
                          :placeholder="$t('user.placeholder_agent')" @select="node => tenantIdHandleSelect(node)"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('user.phoneNo')" prop="phonenumber">
              <el-input v-model.trim="form.phonenumber" :placeholder="$t('user.placeholder_phone')" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('user.email')" prop="email">
              <el-input v-model.trim="form.email" :placeholder="$t('user.placeholder_email')" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" :label="$t('user.account')" prop="userName">
              <el-input v-model.trim="form.userName" :placeholder="$t('user.placeholder_username')" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" :label="$t('user.passwd')" prop="password">
              <el-input v-model.trim="form.password" :placeholder="$t('user.placeholder_passwd')" type="password"
                        maxlength="20" show-password/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('user.sex')">
              <el-select v-model="form.sex" :placeholder="$t('user.placeholder_sex')" class="w-100">
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('user.status')" prop="status">
              <el-radio-group v-model="form.status" :placeholder="$t('user.placeholder_status')">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('user.area')" prop="areaIdList" >
              <treeselect v-model="form.areaIdList" :options="areaTree" :show-count="true" @select="areaChange" @input="areaInput" multiple flat
                          :noResultsText="$t('common.noResultsText')" :placeholder="$t('user.placeholder_area')" :disabled="areaDis"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('user.country')" prop="countryId">
              <el-select v-model="form.countryId" :placeholder="$t('user.placeholder_country')"
                         class="w-100" clearable>
                <el-option
                  v-for="item in countryOptions"
                  :key="item.countryId"
                  :label="item.countryName"
                  :value="item.countryId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('user.role')" prop="roleIds">
              <el-select v-model="form.roleIds" multiple :placeholder="$t('user.placeholder_role')" class="w-100">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('user.remark')">
              <el-input v-model.trim="form.remark" type="textarea" :placeholder="$t('user.placeholder_remark')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  getCountryByAreaId,
  getAgentTree,
  getAreaTree,
  getArea
} from "@/api/system/user";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import CardTable from "@/components/element/table/CardTable.vue";
import CardForm from "@/components/element/form/CardForm.vue";
import Column from "@/components/element/table/Column.vue";

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: {Column, Treeselect, CardForm, CardTable},
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 代理商树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 全部角色选项
      allRoleOptions: [],
      // 国家选项
      countryOptions: [],
      // 地区选项 tree
      areaTree: [],
      // 地区选项
      areaOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        {key: 0, label: `账号`, visible: true},
        {key: 1, label: `用户昵称`, visible: true},
        {key: 2, label: `角色`, visible: true},
        {key: 3, label: `所属`, visible: true},
        {key: 4, label: `区域`, visible: true},
        {key: 5, label: `国家`, visible: true},
        {key: 6, label: `邮箱`, visible: true},
        {key: 7, label: `联系方式`, visible: true},
        {key: 8, label: `状态`, visible: true},
        {key: 9, label: `创建时间`, visible: true}

      ],
      // 表单校验
      rules: {
        userName: [
          {required: true, message: this.$t('user.rule_username'), trigger: "blur"},
          {min: 2, max: 20, message: this.$t('user.rule_uname_len_2_20'), trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: this.$t('user.rule_nick'), trigger: "blur"}
        ],
        password: [
          {required: true, message: this.$t('user.rule_passwd'), trigger: "blur"},
          {min: 5, max: 20, message: this.$t('user.rule_passwd_len_5_20'), trigger: 'blur'},
          {
            pattern: /^[^<>"'|\\]+$/,
            message: this.$t('user.rule_passwd_illegal_char') + "：< > \" ' \\\ |",
            trigger: "blur"
          }
        ],

        deptId: [
          {required: true, message: this.$t('user.rule_agent'), trigger: "change"}
        ],
        email: [
          {required: true, message: this.$t('user.rule_email'), trigger: "blur"},
          {
            type: "email",
            message: this.$t('user.placeholder_correctEmail'),
            trigger: ["blur", "change"]
          }
        ],
        // phonenumber: [
        //   {required: true, message: this.$t('user.rule_phone'), trigger: "blur"},
        //   // {
        //   //   pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        //   //   message: this.$t('user.placeholder_correctPhone'),
        //   //   trigger: "blur"
        //   // }
        // ],
        // 状态
        status: [
          {required: true, message: this.$t('user.rule_status'), trigger: "change"}
        ],
        // 角色
        roleIds: [
          {required: true, message: this.$t('user.rule_role'), trigger: "change"}
        ],
        // 国家
        countryId: [
          {required: true, message: this.$t('user.rule_country'), trigger: "change"}
        ],
        // 区域
        // areaId: [
        //   {required: true, message: this.$t('user.rule_area'), trigger: "change"},
        //   // TODO
        //   {
        //     validator: (rule, value, callback) => {
        //       // 如果角色是销售区域总监，区域不能是全球
        //       const roleIds = this.form.roleIds || [];
        //       for (const roeId of roleIds) {
        //         const role = this.roleOptions.find(item => item.roleId === roeId);
        //         // console.log('role', role)
        //         if (role && role.roleKey === 'area_sales_director') {
        //           // console.log('=======');
        //           if (value === 0) {
        //             callback(new Error('销售区域总监不能选择全球'));
        //           } else {
        //             callback();
        //           }
        //         } else {
        //           callback();
        //         }
        //       }
        //     },
        //     trigger: "change"
        //   },
        // ]
        areaIdList: [
          {required: true, message: this.$t('user.rule_area'), trigger: "change"}
        ]
      },
      areaDis:false
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {

    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
    this.getArea();
    // this.getAreaTree();
    this.getAllRoleOptions();

    // this.getAgentTree();
    this.getList();
  },
  methods: {
    tenantIdHandleSelect(item){
      if(item.id !== 0){
        //代表代理商
        //则需设置新增用户区域，且无法修改
        this.areaDis = true
        this.form.areaIdList = []
        this.form.areaIdList.push(item.areaId);
      }else {
        this.areaDis = false
      }
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      const {createTime, ...params} = this.queryParams;
      // console.log('params', params)
      listUser(params).then(response => {
          this.userList = response.rows;
          this.queryParams.total = response.total;
          this.loading = false;
        }
      );
    },


    // 获取地区下拉框
    getArea() {
      getArea().then(response => {
        this.areaOptions = response.data;
        console.log('allAreaList', this.areaOptions)
      });
    },
    // 获取地区树
    async getAreaTree() {
      const response = await getAreaTree()
      this.areaTree = response.data;
    },

    areaChange(val) {
      // 为空时清空上级区域
      // console.log('val', val)
      // console.log('areaIdList:', this.form.areaIdList)
      // this.$set(this.form, "countryId", '');
      // if (val.id) {
      //   this.getCountryByAreaId(val.id)
      // }
    },
    areaInput(val) {
      // 为空时清空上级区域
      console.log('val', val)
      // console.log('areaIdList:', this.form.areaIdList)

      this.$set(this.form, "countryId", '');
      console.log("清空国家Id")
      if (val && val.length > 0) {
        this.getCountryByAreaId(val)
      }
    },

    async getCountryByAreaId(areaId) {
      const resp = await getCountryByAreaId(areaId);
      console.log("重设国家列表")
      this.countryOptions = resp.data;
        // console.log('nationList', this.countryOptions)
    },

    getAllRoleOptions() {
      getUser().then(response => {
        this.allRoleOptions = response.roles;
      });
    },

    async getAgentTree() {
      const response = await getAgentTree()
      this.deptOptions = response.data;
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      const text = row.status === "0" ? this.$t('common.enabled') : this.$t('common.disabled');
      // this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
      this.$modal.confirm(`${this.$t('common.confirm')}${text}[${row.userName}]?`).then(() => {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(row.status === "0" ? this.$t('common.enableSuccess') : this.$t('common.deactivatSuccess'));
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
        areaId: undefined,
        areaIdList: [],
        countryId: ""
      };
      this.deptOptions = [];
      this.areaTree = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      // this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs?.tree?.setCurrentKey(null);

      this.queryParams.userName = null;
      this.$set(this.queryParams, "userName", null);
      this.$set(this.queryParams, "nickName", null);
      this.$set(this.queryParams, "roleId", null);
      this.$set(this.queryParams, "agentName", null);
      this.$set(this.queryParams, "areaName", null);
      this.$set(this.queryParams, "countryName", null);
      this.$set(this.queryParams, "status", null);
      this.$set(this.queryParams, "createTime", null);
      this.$set(this.queryParams, "beginTime", null);
      this.$set(this.queryParams, "endTime", null);
      this.$set(this.queryParams, 'areaId', null)
      this.$set(this.queryParams, 'areaIdList', null)

      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      await Promise.all([this.getAgentTree(), this.getAreaTree()]);
      getUser().then(response => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.open = true;
        this.title = "添加用户";
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      const response = await getUser(userId);
      // 根据区域id查询国家
      await Promise.all([this.getAgentTree(), this.getAreaTree(), this.getCountryByAreaId(response.data.areaIdList)]);
      this.form = {...response.data}
      this.postOptions = response.posts;
      this.roleOptions = response.roles;
      this.$set(this.form, "postIds", response.postIds);
      this.$set(this.form, "roleIds", response.roleIds);
      console.log("重设国家Id"+ response.data.countryId)
      this.$set(this.form, "countryId", response.data.countryId);
      if(this.form.deptId !== 0) {
        //代表代理商
        //则需设置新增用户区域，且无法修改
        this.areaDis = true
      }
      this.open = true;
      this.title = "修改用户";
      this.form.password = "";


      console.log(this.form)
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({value}) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {
      });
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.areaId = this.form.areaIdList && this.form.areaIdList.join(',');
          if (this.form.userId != undefined) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm(this.$t('common.isDelete')).then(function () {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
      }).catch(() => {
      });
    },
  }
};
</script>

<style scoped>

.w-100 {
  width: 100%;
}
</style>
