<template>
  <div class="detail-wrap">
    <el-form ref="editForm" :model="user">
      <div class="d-header clearfix">
        <div class="fl">
          <i class="el-icon-info"/>
          {{ dataId ? $t1('查看用户') : $t1('新增用户') }}
        </div>
        <div class="fr">
          <el-button type="primary" plain class="button-sty" icon="el-icon-unlock" @click="unlock" v-if="user.locked"
                     v-hasPermi="'user:unlock'">{{ $t1('解锁') }}
          </el-button>
          <el-button type="primary" plain class="button-sty" @click="$baseReload()" icon="el-icon-refresh-right">
            {{ $t1('重置') }}
          </el-button>
          <el-button type="primary" class="button-sty" icon="el-icon-check" @click="saveData">{{ $t1('保存') }}
          </el-button>
        </div>
      </div>
      <baseTabs>
        <baseTabPane :label="$t1('基本信息')">
          <template #default>
            <table class="table-detail">
              <tbody>
              <tr>
                <th>
                  <em class="f-red">*</em>
                  {{ $t1('登录名') }}
                </th>
                <td colspan="3">
                  <el-form-item prop="loginAccount" :rules="[{ required: true, trigger: 'blur' }]">
                    <template v-if="dataId">
                      <el-input size="small" v-model="user.loginAccount" maxlength="255" autocomplete="off"
                                lay-verify="required" required="" :readonly="true"/>
                    </template>
                    <template v-else>
                      <el-input size="small" v-model="user.loginAccount" maxlength="255" autocomplete="off"
                                lay-verify="required" required="" clearable/>
                    </template>
                  </el-form-item>
                </td>
                <td colspan="4">
                  <span class="tips">{{ $t1('注：登录名必须以“dev_”开头') }}</span>
                </td>
              </tr>
              <tr>
                <th>
                  <em class="f-red">*</em>
                  {{ $t1('姓名') }}
                </th>
                <td colspan="3">
                  <el-form-item prop="nickName" :rules="[{ required: true, trigger: 'blur' }]">
                    <el-input size="small" v-model="user.nickName" maxlength="200" lay-verify="required" required=""
                              clearable/>
                  </el-form-item>
                </td>
              </tr>
              <tr v-if="userInfo.flag==6 || userInfo.flag==7">
                <th>
                  <em class="f-red">*</em>
                  {{ $t1('用户组') }}
                </th>
                <td colspan="3">
                  <el-form-item prop="groupCode" :rules="[{ required: true, trigger: 'blur' }]">
                    <el-select v-model="user.groupCode">
                      <el-option v-for="(item,index) in userGroups" :key="index" :value="item.groupCode"
                                 :label="item.groupName"></el-option>
                    </el-select>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <th>
                  <em class="f-red" v-if="!dataId">*</em>
                  {{ $t1('密码') }}
                </th>
                <td>
                  <el-form-item prop="password" :rules="passRules">
                    <el-input size="small" type="password" v-model="user.password" show-password maxlength="255"
                              autocomplete="off" auto-complete="new-password" clearable/>
                  </el-form-item>
                </td>
                <th>
                  <em class="f-red" v-if="!dataId">*</em>
                  {{ $t1('确认密码') }}
                </th>
                <td>
                  <el-form-item prop="rePassword" :rules="pass2Rules">
                    <el-input
                      size="small"
                      type="password"
                      v-model="user.rePassword"
                      show-password
                      maxlength="255"
                      autocomplete="off"
                      auto-complete="new-password"
                      lay-verify="confirmPass"
                      clearable
                    />
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <th>{{ $t1('设置') }}</th>
                <td>
                  <el-checkbox :label="$t1('是否启用')" v-model="user.enabled"></el-checkbox>
                </td>
              </tr>
              <tr>
                <th>{{ $t1('创建时间') }}</th>
                <td>{{ user.createDate }}</td>
                <th>{{ $t1('更新时间') }}</th>
                <td>{{ user.modifyDate }}</td>
              </tr>
              </tbody>
            </table>
          </template>
        </baseTabPane>
        <baseTabPane :label="$t1('表单分类信息')">
          <template #default>
            <vxe-grid
              ref="table-m1"
              :data="menuKindAuthDTOs"
              v-bind="vxeOption"
              @resizable-change="$vxeTableUtil.onColumnWitchChange"
              @custom="$vxeTableUtil.customHandle"
            ></vxe-grid>
          </template>
        </baseTabPane>
      </baseTabs>
    </el-form>
    <groudDialog v-if="showGroupDialog" :visiable.sync="showGroupDialog"
                 @confirm="confirmGroupDialog" multi="false"/>
  </div>
</template>

<script>
import xeUtils from "xe-utils";
import groudDialog from "@base/views/user/groups/dialog.vue";
import {getBdEnv} from "@base/api/user";

export default {
  name: 'UserEdit',
  components: {groudDialog},
  props: ['_dataId', 'userType', 'flag'],
  data() {
    var validatePass = (rule, value, callback) => {
      const isPassRequired = !this.dataId;
      if (isPassRequired && (value == '' || value == undefined)) {
        callback(new Error(this.$t1('密码不能为空')));
      } else {
        callback();
      }
      this.$refs.editForm.validateField('rePassword');
    };
    var validatePass2 = (rule, value, callback) => {
      const isPassRequired = !this.dataId;
      const rePassword = value != undefined ? value : '';
      const password = this.user.password != undefined ? this.user.password : '';

      if (isPassRequired && rePassword == '') {
        callback(new Error(this.$t1('确认密码不能为空')));
      } else if (rePassword != password) {
        callback(new Error(this.$t1('两次输入密码不一致!')));
      } else {
        callback();
      }
    };

    return {
      dataId: '',
      hBtn: true,
      user: {
        userCompanyInfoDTOs: [],
        userSaleOrgDTOs: [],
        userRoleDTOs: [],
        gender: null,
        enabled: true,
        userType: null,
        countryName: null,
        countryCode: null,
        flag: 8,
        groupCode: null
      },
      companyInfoOption: {},
      userRoleOption: {},
      showRoleDialog: false,
      showCompanyDialog: false,
      showSaleOrgDialog: false,
      showPositionDialog: false,
      saleOrgPositionIndex: 0,
      passRules: [{validator: validatePass, trigger: 'blur', required: false}],
      pass2Rules: [{validator: validatePass2, trigger: 'blur', required: false}],
      activeName: 'first',
      userCustomerListDTO: {
        userCustomerDTOs: []
      },
      customerOption: {},
      showCustomerDialog: false,
      exportOption: {
        prefix: USER_PREFIX,
        title: this.$t1('用户'),
        codes: ["USEREXCEL", "USERPDF", "USERPRINT", "USERHIPRINT"],
        param: () => {
          return [{id: this.dataId}];
        }
      },
      showExtendedProperties: false,
      radio1: '0',
      companyInfo: {},
      vxeOptionMap: {},
      gridRoleDataMap: {},
      gridSaleOrgDataMap: {},
      distributorCode: 'distributor',
      distributorRole: null,
      outUserCodes: [],
      roleDialogParam: {queryAll: true},
      tempStorageOption: {
        storageType: "user",
        data: () => {
          return this.user;
        },
        chooseConfirm: (tempStorageData) => {
          this.user = tempStorageData;
        },
        saveConfirm: () => {
        }
      },
      showCountryDialog: false,
      userInfo: {},
      userGroups: [],
      showGroupDialog: false,
      vxeOption: {},
      menuKindAuthDTOs: [],
      isDev: true
    };
  },
  computed: {
    hasCurrentCompany() {
      return this.user.userCompanyInfoDTOs.find(item => item.companyCode == this.companyInfo.companyCode) != null;
    }
  },
  created() {
    if (this._dataId && !isNaN(this._dataId)) this.dataId = this._dataId;
  },
  async mounted() {

    this.getUserInfo()
    this.getUserGroups()
    this.getData();
    this.getConpanyInfo()
    await this.initBdEnv();
    this.initTableM1();
  },
  methods: {
    getData() {
      if (this.dataId && !isNaN(this.dataId)) {
        this.isEdit = true;
        this.$commonHttp({
          aes: true,
          url: USER_PREFIX + `/user/get`,
          method: `post`,
          data: {
            id: this.dataId
          },
          isLoading: true,
          modalStrictly: true,
          success: res => {
            let user = res.objx || {};
            user.userCompanyInfoDTOs = this.user.userCompanyInfoDTOs;
            user.userSaleOrgDTOs = this.user.userSaleOrgDTOs;
            user.userRoleDTOs = this.user.userRoleDTOs;
            this.user = user;
            this.user.password = '';

            this.showExtendedProperties = true;
          }
        });
      } else {
        this.user.gender = 1;
        this.isEdit = false;
        this.showExtendedProperties = true;
      }
    },
    saveData() {
      let companyCode = this.companyInfo.companyCode;

      this.$refs.editForm.$baseValidate(valid => {
        if (valid) {
          if (!this.isEdit) {
            let loginAccount = this.user.loginAccount;
            if (!loginAccount.startsWith('dev_')) {
              this.$message({
                message: this.$t1('登录名必须以“dev_”开头'),
                type: 'error',
                duration: 2000,
              });
              return
            }
          }
          this.$baseConfirm(this.$t1('您确定要保存吗？')).then(() => {
            var url = USER_PREFIX + (this.isEdit ? '/user/update' : '/user/save');
            this.$http({
              aes: true,
              url: url,
              method: `post`,
              data: this.user,
              isLoading: true,
              success: res => {
                this.$message({
                  message: res.content,
                  type: 'success',
                  duration: 500,
                  onClose: t => {
                    if (this.isEdit) {
                      this.$baseReload();
                    } else {
                      this.$baseReload({
                        updateParam: {
                          _dataId: res.objx
                        }
                      });
                    }
                  }
                });
              }
            });
          });
        }
      });
    },
    getSaleOrgData() {
      if (this.dataId) {
        this.$http({
          aes: true,
          url: USER_PREFIX + '/user/getUserSaleOrg',
          method: `post`,
          data: {id: this.dataId},
          isLoading: true,
          modalStrictly: true,
          success: res => {
            // this.$refs.saleOrgGrid.loadData(res.objx || []);
            let rows = res.objx || [];
            if (rows.length) {
              // this.gridSaleOrgDataMap = xeUtils.groupBy(rows, 'companyCode');
              Object.assign(this.gridSaleOrgDataMap, xeUtils.groupBy(rows, 'companyCode'));
            }
            this.user.userSaleOrgDTOs = rows;
          }
        });
      }
    },
    getUserRoleData() {
      if (this.dataId) {
        this.$http({
          aes: true,
          url: USER_PREFIX + '/user/getUserRole',
          method: `post`,
          data: {id: this.dataId},
          isLoading: true,
          modalStrictly: true,
          success: res => {
            let rows = res.objx || [];
            if (rows.length) {
              // this.gridRoleDataMap = xeUtils.groupBy(rows, 'companyCode');
              Object.assign(this.gridRoleDataMap, xeUtils.groupBy(rows, 'companyCode'));
            }
            this.user.userRoleDTOs = rows;
          }
        });
      }
    },
    deleteSaleOrgItem(row, index, $table) {
      $table.remove(row);
      this.gridSaleOrgDataMap[row.companyCode].splice(index, 1);
    },
    getCompanyInfoData(callback) {
      if (this.dataId) {
        this.$http({
          aes: true,
          url: USER_PREFIX + '/user/getUserCompanyInfo',
          method: `post`,
          data: {id: this.dataId},
          isLoading: true,
          modalStrictly: true,
          success: res => {
            let rows = res.objx || [];
            rows.forEach(row => {
              this.gridRoleDataMap[row.companyCode] = [];
              this.gridSaleOrgDataMap[row.companyCode] = [];
            })
            this.user.userCompanyInfoDTOs = rows;
            callback && callback();
          }
        });
      }
    },
    confirmInsertCompany(rows, callback) {
      if (rows.length > 0) {
        const tableData = this.user.userCompanyInfoDTOs;
        const map = {};
        tableData.forEach(function (item) {
          map[item.companyCode] = 1;
        });
        var items = [];
        rows.forEach(row => {
          const item = {companyCode: row.companyCode, companyName: row.companyName, guid: null};
          if (!map[item.companyCode]) {
            items.push(item);
          }
          this.gridRoleDataMap[item.companyCode] = []
          this.gridSaleOrgDataMap[item.companyCode] = []
        });
        // $grid.insertAt(items, -1);
        this.user.userCompanyInfoDTOs.splice(0, 0, ...items);
        // this.user.userCompanyInfoDTOs = this.user.userCompanyInfoDTOs.concat(items);
      }
      callback && callback();
    },
    deleteCompany(row, index) {
      let companyCode = row.companyCode;
      this.user.userCompanyInfoDTOs.splice(index, 1);
      this.gridSaleOrgDataMap[row.companyCode] = [];
      this.gridRoleDataMap[row.companyCode] = [];
      this.user.userSaleOrgDTOs = this.user.userSaleOrgDTOs.filter(item => item.companyCode != companyCode);
      this.user.userRoleDTOs = this.user.userRoleDTOs.filter(item => item.companyCode != companyCode);
    },
    getConpanyInfo() {
      this.$http({
        aes: true,
        url: USER_PREFIX + '/company_info/getCurrent',
        method: `post`,
        isLoading: true,
        success: res => {
          this.companyInfo = res.objx || {};
          let companyCode = this.companyInfo.companyCode;
          if (!this.isEdit) {
            this.addCurrentCompany();
          } else {
            this.getCompanyInfoData(() => {

            });
          }
        }
      });
    },
    isCurrentCompany(companyCode) {
      return this.companyInfo.companyCode == companyCode;
    },
    addCurrentCompany(callback) {
      this.confirmInsertCompany([this.companyInfo], callback);
    },
    unlock() {
      this.$baseConfirm(this.$t1('您确定要解锁吗？')).then(() => {
        var url = USER_PREFIX + '/user/unlockLoginAccount';
        this.$http({
          aes: true,
          url: url,
          method: `post`,
          data: {
            id: this.user.id
          },
          isLoading: true,
          success: res => {
            this.$message({
              message: res.content,
              type: 'success',
              duration: 500,
              onClose: t => {
                this.$baseReload();
              }
            });
          }
        });
      });
    },
    confirmCountry(rows) {
      if (rows.length) {
        let row = rows[0];
        this.user.countryName = row.countryName;
        this.user.countryCode = row.countryCode;
      }
    },
    getUserInfo() {
      return this.$http({
        aes: true,
        url: USER_PREFIX + '/user/currentUser',
        method: 'post',
        success: res => {
          let userInfo = res.objx;
          this.userInfo = userInfo;
          if (!this.isEdit) {
            this.user.groupCode = userInfo.groupCode;
          }
        }
      });
    },
    getUserGroups() {
      return this.$http({
        aes: true,
        url: USER_PREFIX + '/groups/listPage',
        method: 'post',
        data: {},
        success: res => {
          this.userGroups = res.objx?.records || [];
        }
      });
    },
    initTableM1() {
      const tableOption = {
        vue: this,
        tableRef: 'table-m1',
        tableName: 'edit-user-menuKind-m1',
        columns: [
          {type: 'checkbox', fixed: 'left', width: 48, resizable: false},
          {
            title: this.$t1('表单分类名称'),
            field: 'menuKindName',
            width: 350,
            fixed: 'left'
          },
          {
            title: this.$t1('编辑'),
            field: 'editAuth',
            width: 150,
            slots: {
              default: ({row}) => {
                if (row.editAuth) {
                  return [<div class="txt-status">{this.$t1('是')}</div>];
                } else {
                  return [<div class="txt-status s-3">{this.$t1('否')}</div>];
                }
              }
            }
          },
          {
            title: this.$t1('导出发布'),
            field: 'exportAuth',
            width: 150,
            slots: {
              default: ({row}) => {
                if (row.exportAuth) {
                  return [<div class="txt-status">{this.$t1('是')}</div>];
                } else {
                  return [<div class="txt-status s-3">{this.$t1('否')}</div>];
                }
              }
            }
          },
          ...(this.isDev ? [{
            title: this.$t1('可选导出发布类型'),
            field: 'selectTypeAuth',
            width: 200,
            slots: {
              default: ({row}) => {
                if (row.selectTypeAuth) {
                  return [<div class="txt-status">{this.$t1('是')}</div>];
                } else {
                  return [<div class="txt-status s-3">{this.$t1('否')}</div>];
                }
              }
            }
          }] : []),
          {
            width: 47,
            fixed: 'right',
            title: '',
            sortable: false
          }
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
      });
      if (this.dataId) {
        this.$http({
          aes: true,
          url: USER_PREFIX + `/menu_kind_auth/list`,
          method: `post`,
          data: {
            userId: this.dataId
          },
          isLoading: true,
          modalStrictly: true,
          success: res => {
            this.menuKindAuthDTOs = res.objx || [];
          }
        });
      }
    },
    initBdEnv() {
      return getBdEnv({
        success: res => {
          this.isDev = res.objx == "dev"
        }
      });
    },
  }
};
</script>
