<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">
          <temp-storage-button
            :option="tempStorageOption"
            v-if="!dataId"
          ></temp-storage-button>
          <base-input-export
            :option="exportOption"
            :parent-target="_self"
            v-if="dataId"
          />
          <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>

                  <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>
                  <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>

                  <th>{{ $t1("性别") }}</th>
                  <td>
                    <el-radio-group v-model="user.gender">
                      <el-radio :label="1">{{ $t1("男") }}</el-radio>
                      <el-radio :label="2">{{ $t1("女") }}</el-radio>
                    </el-radio-group>
                  </td>
                  <th>
                    {{ $t1("员工编码") }}
                  </th>
                  <td>
                    <el-form-item
                      prop="empNo"
                      :rules="[{ required: false, trigger: 'blur' }]"
                    >
                      <el-input
                        size="small"
                        v-model="user.empNo"
                        maxlength="200"
                        clearable
                      />
                    </el-form-item>
                  </td>
                </tr>

                <tr>
                  <th>{{ $t1("出生日期") }}</th>
                  <td>
                    <el-date-picker
                      size="small"
                      v-model="user.birth"
                      type="date"
                      :placeholder="$t1('选择日期')"
                      value-format="yyyy-MM-dd"
                      clearable
                    />
                  </td>
                  <th>{{ $t1("邮编") }}</th>
                  <td>
                    <el-input
                      size="small"
                      v-model="user.zipCode"
                      maxlength="255"
                      clearable
                    />
                  </td>
                  <th>{{ $t1("手机") }}</th>
                  <td>
                    <el-form-item
                      prop="mobile"
                      :rules="[{ required: false, trigger: 'blur' }]"
                    >
                      <el-input
                        size="small"
                        v-model="user.mobile"
                        type="text"
                        maxlength="255"
                        autocomplete="off"
                        lay-verify="required|phone"
                        clearable
                      />
                    </el-form-item>
                  </td>
                  <th>{{ $t1("设置") }}</th>
                  <td>
                    <el-checkbox
                      :label="$t1('是否启用')"
                      v-model="user.enabled"
                    ></el-checkbox>
                  </td>
                </tr>

                <tr>
                  <th>
                    {{ $t1("邮箱") }}
                  </th>
                  <td>
                    <el-form-item
                      prop="email"
                      :rules="[{ required: false, trigger: 'blur' }]"
                    >
                      <el-input
                        size="small"
                        v-model="user.email"
                        maxlength="200"
                        clearable
                      />
                    </el-form-item>
                  </td>
                  <!--                <th v-if="flag!=='2'">
                                  GUID
                                </th>
                                <td v-if="flag!=='2'">
                                  <el-form-item prop="guid" :rules="[{ required: false, trigger: 'blur' }]">
                                    <el-input size="small" v-model="user.guid" maxlength="200" clearable/>
                                  </el-form-item>
                                </td>-->
                  <th>{{ $t1("地址") }}</th>
                  <td colspan="3">
                    <el-input
                      size="small"
                      v-model="user.address"
                      class="b"
                      maxlength="255"
                      clearable
                    />
                  </td>
                </tr>
                <tr>
                  <th>
                    {{ $t1("国家") }}
                  </th>
                  <td colspan="3">
                    <el-form-item
                      prop="countryName"
                      :rules="[{ required: false, trigger: 'blur' }]"
                    >
                      <el-input
                        class="search-input"
                        v-model="user.countryName"
                        clearable
                        @clear="
                          user.countryName = null;
                          user.countryCode = null;
                        "
                        v-el-readonly
                      >
                        <i
                          slot="suffix"
                          class="el-input__icon el-icon-search"
                          @click="showCountryDialog = true"
                        ></i>
                      </el-input>
                    </el-form-item>
                  </td>
                  <th>
                    {{ $t1("是否锁定") }}
                  </th>
                  <td>
                    {{ user.locked ? $t1("是") : $t1("否") }}
                  </td>
                </tr>
                <tr>
                  <th>
                    {{ $t1("地区") }}
                  </th>
                  <td colspan="3">
                    <el-form-item
                      prop="areaName"
                      :rules="[{ required: false, trigger: 'blur' }]"
                    >
                      <el-input
                        class="search-input"
                        v-model="user.areaName"
                        clearable
                        @clear="
                          user.areaName = null;
                          user.areaId = null;
                        "
                        v-el-readonly
                      >
                        <i
                          slot="suffix"
                          class="el-input__icon el-icon-search"
                          @click="showAreaDialog = true"
                        ></i>
                      </el-input>
                    </el-form-item>
                  </td>
                </tr>
                <tr v-if="userType == 2">
                  <th>
                    {{ $t1("签约人") }}
                  </th>
                  <td>
                    <el-form-item
                      prop="signatoryName"
                      :rules="[{ required: false, trigger: 'blur' }]"
                    >
                      <el-input
                        size="small"
                        v-model="user.signatoryName"
                        maxlength="200"
                        clearable
                      />
                    </el-form-item>
                  </td>
                  <th>
                    {{ $t1("签约人电话") }}
                  </th>
                  <td>
                    <el-form-item
                      prop="signatoryMobile"
                      :rules="[{ required: false, trigger: 'blur' }]"
                    >
                      <el-input
                        size="small"
                        v-model="user.signatoryMobile"
                        maxlength="200"
                        clearable
                      />
                    </el-form-item>
                  </td>
                </tr>
                <tr>
                  <th>{{ $t1("坐席ID") }}</th>
                  <td>
                    <el-input
                      size="small"
                      v-model="user.agentId"
                      maxlength="200"
                      clearable
                    />
                  </td>
                  <th>{{ $t1("技能组ID") }}</th>
                  <td>
                    <el-input
                      size="small"
                      v-model="user.groupId"
                      maxlength="200"
                      clearable
                    />
                  </td>
                  <th>{{ $t1("手机/sip号") }}</th>
                  <td>
                    <el-input
                      size="small"
                      v-model="user.voipAccount"
                      maxlength="200"
                      clearable
                    />
                  </td>
                  <th>{{ $t1("登录方式") }}</th>
                  <td>
                    <el-select
                      size="small"
                      v-model="user.callWay"
                      maxlength="200"
                      clearable
                    >
                      <el-option label="sip话机" value="2"></el-option>
                      <el-option label="手机" value="3"></el-option>
                    </el-select>
                  </td>
                </tr>
                <tr>
                  <th>{{ $t1("头像") }}</th>
                  <td colspan="7">
                    <baseUpload
                      :limit="1"
                      accept="image/png, image/jpeg"
                      multi="false"
                      :file.sync="user.headPhotoUrl"
                      dataType="medium"
                    ></baseUpload>
                  </td>
                </tr>
                <tr>
                  <th>{{ $t1("创建人") }}</th>
                  <td>{{ user.createBy }}</td>
                  <th>{{ $t1("创建时间") }}</th>
                  <td>{{ user.createDate }}</td>
                  <th>{{ $t1("更新人") }}</th>
                  <td>{{ user.modifyBy }}</td>
                  <th>{{ $t1("更新时间") }}</th>
                  <td>{{ user.modifyDate }}</td>
                </tr>
              </tbody>
            </table>
          </template>
        </baseTabPane>
        <baseTabPane :label="$t1('组织信息')">
          <template #button>
            <el-button
              class="button-sty"
              @click="addCurrentCompany()"
              icon="el-icon-search"
              v-if="!hasCurrentCompany"
            >
              {{ $t1("新增组织权限") }}
            </el-button>
          </template>
          <template #default>
            <div class="style1">
              <div
                class="d-item"
                v-for="(item, index1) in user.userCompanyInfoDTOs"
                :key="index1"
              >
                <div class="title">
                  <b>{{ item.companyName }}</b>
                  <el-button
                    class="button-sty"
                    icon="el-icon-delete"
                    v-if="isCurrentCompany(item.companyCode)"
                    @click="deleteCompany(item, index1)"
                    >{{ $t1("删除") }}
                  </el-button>
                </div>
                <div class="title-form">
                  <span>
                    <el-form-item
                      label="GUID"
                      :prop="'userCompanyInfoDTOs.' + index1 + '.guid'"
                      :rules="[{ required: false, trigger: 'blur' }]"
                    >
                      <el-input
                        size="small"
                        v-model="item.guid"
                        maxlength="200"
                        clearable
                      />
                    </el-form-item>
                  </span>
                  <span>
                    <el-form-item
                      label="是否默认组织"
                      :prop="'userCompanyInfoDTOs.' + index1 + '.defaults'"
                      :rules="[{ required: false, trigger: 'blur' }]"
                    >
                      <el-checkbox
                        v-model="item.defaults"
                        @change="changeCompanyDefault(item)"
                      ></el-checkbox>
                    </el-form-item>
                  </span>
                </div>
                <div class="m-2">
                  <div class="d-item" style="width: 65%">
                    <div class="title">
                      <b>{{ $t1("机构信息") }}</b>
                      <el-button
                        class="button-sty"
                        icon="el-icon-search"
                        @click="showSaleOrgDialog = true"
                        v-if="isCurrentCompany(item.companyCode)"
                        >{{ $t1("选择机构") }}
                      </el-button>
                    </div>
                    <div class="grid-h">
                      <vxe-grid
                        :ref="'saleOrgGrid-' + item.companyCode"
                        :data="item.saleOrgData"
                        v-bind="item.saleOrgGridOption"
                        @resizable-change="$vxeTableUtil.onColumnWitchChange"
                        @custom="$vxeTableUtil.customHandle"
                      >
                        <template #position="{ row, rowIndex, $table }">
                          <el-input
                            class="search-input"
                            :value="getSelectPositionName(row)"
                            clearable
                            @clear="
                              row.userSaleOrgPositionDTOs = [];
                              $forceUpdate();
                            "
                            v-el-readonly
                            v-if="companyInfo.companyCode == row.companyCode"
                          >
                            <i
                              slot="suffix"
                              class="el-input__icon el-icon-search"
                              @click="
                                openSelectPositionDialog(row, rowIndex, $table)
                              "
                            ></i>
                          </el-input>
                          <template v-else>
                            {{ getSelectPositionName(row) }}
                          </template>
                        </template>
                      </vxe-grid>
                    </div>
                  </div>
                  <div class="d-item" style="width: 35%">
                    <div class="title">
                      <b>{{ $t1("角色信息") }}</b>
                      <el-button
                        class="button-sty"
                        icon="el-icon-search"
                        @click="showRoleDialog = true"
                        v-if="isCurrentCompany(item.companyCode)"
                        >{{ $t1("选择角色") }}
                      </el-button>
                    </div>
                    <div class="grid-h">
                      <vxe-grid
                        :ref="'userRoleGrid-' + item.companyCode"
                        :data="item.roleData"
                        v-bind="item.roleGridOption"
                        @resizable-change="$vxeTableUtil.onColumnWitchChange"
                        @custom="$vxeTableUtil.customHandle"
                      ></vxe-grid>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </baseTabPane>
      </baseTabs>
    </el-form>
    <roleDialog
      v-if="showRoleDialog"
      :visiable.sync="showRoleDialog"
      @confirm="confirmRole"
      :param="roleDialogParam"
    />
    <companyDialog
      v-if="showCompanyDialog"
      :visiable.sync="showCompanyDialog"
      @confirm="confirmInsertCompany"
    />
    <saleOrgDialog
      v-if="showSaleOrgDialog"
      :visiable.sync="showSaleOrgDialog"
      @confirm="confirmInsertSaleOrg"
      :param="{ queryAll: true }"
    />
    <positionDialog
      v-if="showPositionDialog"
      :visiable.sync="showPositionDialog"
      :rows="positionDialogDatas"
      @confirm="confirmInsertPosition"
      :param="{ queryAll: true }"
    />
    <countryDialog
      v-if="showCountryDialog"
      :visiable.sync="showCountryDialog"
      @confirm="confirmCountry"
      multi="false"
    />
    <areaDialog
      v-if="showAreaDialog"
      :visiable.sync="showAreaDialog"
      @confirm="confirmArea"
      multi="false"
    />
  </div>
</template>

<script>
import xeUtils from "xe-utils";
import tempStorageButton from "@base/components/tempStorage/index.vue";

export default {
  name: "UserEdit",
  components: {
    roleDialog: () => import("../../../views/user/role/dialog.vue"),
    companyDialog: () => import("../../../views/user/company_info/dialog.vue"),
    saleOrgDialog: () => import("../../../views/user/sale_org/dialog.vue"),
    positionDialog: () => import("../../../views/user/position/dialog.vue"),
    countryDialog: () => import("../../../views/user/country/dialog.vue"),
    areaDialog: () => import("../../../views/user/area/dialog.vue"),
    tempStorageButton,
  },
  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,
        areaName: null,
        areaId: null,
      },
      companyTableData: [],
      vxeOption: {},
      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: {},
      distributorCode: "distributor",
      distributorRole: null,
      outUserCodes: [],
      roleDialogParam: { queryAll: true },
      tempStorageOption: {
        storageType: "user",
        data: () => {
          this.handleData();
          return this.getReqFormData();
        },
        chooseConfirm: (tempStorageData) => {
          this.user = tempStorageData;
          let map = xeUtils.groupBy(this.user.userRoleDTOs, "companyCode");
          Object.keys(map).forEach((key) => {
            let comapnyDTO = this.getCompanyDTO(key);
            comapnyDTO.roleData = map[key];
          });
        },
        saveConfirm: () => {},
      },
      showCountryDialog: false,
      showAreaDialog: false,
    };
  },
  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.getEainsGroupDTO();
    await this.initOutUserRoleCode();
    await this.initDistributorRole();
    this.getData();
    this.getConpanyInfo();
  },
  methods: {
    getData() {
      if (this.dataId && !isNaN(this.dataId)) {
        this.isEdit = true;
        this.$commonHttp({
          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;
      }
    },
    getReqFormData() {
      let userCompanyInfoDTOs = this.user.userCompanyInfoDTOs.map((item) => {
        return {
          ...item,
          saleOrgGridOption: null,
          roleGridOption: null,
          saleOrgData: null,
          roleData: null,
        };
      });
      let formData = {
        ...this.user,
        userCompanyInfoDTOs,
      };
      return formData;
    },
    saveData() {
      let companyCode = this.companyInfo.companyCode;
      this.handleData();
      if (this.userType == 2) {
        //外部用户
        let currentUserCompanyInfo = this.user.userCompanyInfoDTOs.find(
          (item) => item.companyCode == companyCode
        );
        if (currentUserCompanyInfo) {
          let rows = this.user.userRoleDTOs.filter(
            (item) => item.companyCode == companyCode
          );
          if (!rows.length) {
            this.$baseAlert(this.$t1("请维护角色"));
            return;
          }
        }
      }
      this.$refs.editForm.$baseValidate((valid) => {
        if (valid) {
          this.$baseConfirm(this.$t1("您确定要保存吗？")).then(() => {
            var url =
              USER_PREFIX + (this.isEdit ? "/user/update" : "/user/save");
            let formData = this.getReqFormData();
            this.$http({
              url: url,
              method: `post`,
              data: formData,
              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({
          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) {
              let map = xeUtils.groupBy(rows, "companyCode");
              Object.keys(map).forEach((key) => {
                let companyDTO = this.getCompanyDTO(key);
                companyDTO.saleOrgData = map[key];
              });
            }
            this.user.userSaleOrgDTOs = rows;
          },
        });
      }
    },
    getUserRoleData() {
      if (this.dataId) {
        this.$http({
          url: USER_PREFIX + "/user/getUserRole",
          method: `post`,
          data: { id: this.dataId },
          isLoading: true,
          modalStrictly: true,
          success: (res) => {
            let rows = res.objx || [];
            if (rows.length) {
              let map = xeUtils.groupBy(rows, "companyCode");
              Object.keys(map).forEach((key) => {
                let companyDTO = this.getCompanyDTO(key);
                companyDTO.roleData = map[key];
              });
            }
            this.user.userRoleDTOs = rows;
          },
        });
      }
    },
    deleteSaleOrgItem(row, index, $table) {
      this.getCompanyDTO(row.companyCode).saleOrgData.splice(index, 1);
    },
    getCompanyInfoData(callback) {
      if (this.dataId) {
        this.$http({
          url: USER_PREFIX + "/user/getUserCompanyInfo",
          method: `post`,
          data: { id: this.dataId },
          isLoading: true,
          modalStrictly: true,
          success: (res) => {
            let rows = res.objx || [];
            let companyTableData = [];
            rows.forEach((row) => {
              Object.assign(row, {
                saleOrgGridOption: {},
                roleGridOption: {},
                saleOrgData: [],
                roleData: [],
              });
            });

            this.user.userCompanyInfoDTOs = rows;
            callback && callback();
          },
        });
      }
    },
    initSaleOrg(companyCode) {
      let companyDTO = this.getCompanyDTO(companyCode);
      if (Object.keys(companyDTO.saleOrgGridOption).length) {
        return;
      }
      let tableRef = "saleOrgGrid-" + companyCode;
      const tableOption = {
        vue: this,
        tableRef: tableRef,
        tableName: "editUser-saleOrgGrid-" + companyCode,
        columns: [
          { type: "checkbox", fixed: "left", width: 48, resizable: false },
          { title: this.$t1("机构名称"), field: "saleOrgName", width: 200 },
          { title: this.$t1("机构编码"), field: "sn", width: 200 },
          { title: this.$t1("上级机构"), field: "treePathName", width: 200 },
          {
            title: this.$t1("岗位"),
            field: "position",
            width: 150,
            slots: {
              default: "position",
            },
          },
          {
            title: this.$t1("是否默认"),
            field: "defaults",
            width: 120,
            slots: {
              default: ({ row, $table, rowIndex }) => {
                var isDefault = row.defaults || false;
                let disabled = this.companyInfo.companyCode != row.companyCode;
                return [
                  <el-checkbox
                    v-model={isDefault}
                    disabled={disabled}
                    onchange={() => {
                      let companyDTO = this.getCompanyDTO(row.companyCode);
                      companyDTO.saleOrgData.forEach((item, index) => {
                        if (index !== rowIndex) {
                          item.defaults = false;
                        }
                      });
                      this.$nextTick(() => {
                        row.defaults = true;
                      });
                    }}
                  />,
                ];
              },
            },
          },
          {
            width: 47,
            fixed: "right",
            title: "",
            sortable: false,
            slots: {
              default: ({ row, rowIndex, $table }) => {
                if (this.companyInfo.companyCode == row.companyCode) {
                  return [
                    <a
                      href="javascript:void(0);"
                      class="a-link"
                      onclick={() => {
                        this.deleteSaleOrgItem(row, rowIndex, $table);
                      }}
                    >
                      <el-tooltip
                        enterable={false}
                        effect="dark"
                        content={this.$t1("删除")}
                        placement="top"
                        popper-class="tooltip-skin"
                      >
                        <i class="el-icon-delete" />
                      </el-tooltip>
                    </a>,
                  ];
                }
              },
            },
          },
        ],
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then((opts) => {
        companyDTO.saleOrgGridOption = opts;
      });
    },
    initUserRole(companyCode) {
      let companyDTO = this.getCompanyDTO(companyCode);
      if (Object.keys(companyDTO.roleGridOption).length) {
        return;
      }
      let userType = this.userType;
      const tableOption = {
        vue: this,
        tableRef: "userRoleGrid-" + companyCode,
        tableName: "editUser-userRoleGrid-" + companyCode,
        columns: [
          { type: "checkbox", fixed: "left", width: 48, resizable: false },
          {
            title: this.$t1("角色名称"),
            field: "name",
            width: 200,
            slots: {
              default: ({ row }) => {
                if (!row.isAdd) {
                  return row.roleName;
                } else {
                  return row.name;
                }
              },
            },
          },
          {
            width: 47,
            fixed: "right",
            title: "",
            sortable: false,
            slots: {
              default: ({ row, rowIndex, $table }) => {
                if (this.companyInfo.companyCode == row.companyCode) {
                  return [
                    <a
                      href="javascript:void(0);"
                      class="a-link"
                      onclick={() => {
                        this.deleteRoleItem(row, rowIndex, $table);
                      }}
                    >
                      <el-tooltip
                        enterable={false}
                        effect="dark"
                        content={this.$t1("删除")}
                        placement="top"
                        popper-class="tooltip-skin"
                      >
                        <i class="el-icon-delete" />
                      </el-tooltip>
                    </a>,
                  ];
                }
              },
            },
          },
        ],
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then((opts) => {
        companyDTO.roleGridOption = opts;
      });
    },
    confirmRole(rows) {
      if (rows.length > 0) {
        let companyCode = this.companyInfo.companyCode;
        let companyDTO = this.getCompanyDTO(companyCode);
        let outUserCodes = this.outUserCodes;
        if (this.userType === 1) {
          //组织用户
          rows = rows.filter((row) => !outUserCodes.includes(row.code));
        } else if (this.userType === 2) {
          //外部用户
          rows = rows.filter((row) => outUserCodes.includes(row.code));
        }

        const $grid = this.$refs["userRoleGrid-" + companyCode][0];
        const tableData = companyDTO.roleData;
        const map = {};
        tableData.forEach(function (item) {
          map[item.roleId] = 1;
        });
        var items = [];
        rows.forEach((row) => {
          const item = {
            roleId: row.id,
            roleName: row.name,
            companyCode: companyCode,
            companyName: row.companyName,
          };
          if (!map[item.roleId]) {
            items.push(item);
          }
        });

        companyDTO.roleData.push(...items);
      }
    },
    deleteRoleItem(row, index, $table) {
      let companyDTO = this.getCompanyDTO(row.companyCode);
      $table.remove(row);
      companyDTO.roleData.splice(index, 1);
    },
    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,
            defaults: false,
            saleOrgGridOption: {},
            roleGridOption: {},
            saleOrgData: [],
            roleData: [],
          };
          if (!map[item.companyCode]) {
            items.push(item);
          }
        });
        // $grid.insertAt(items, -1);
        this.user.userCompanyInfoDTOs.splice(0, 0, ...items);
        if (this.user.userCompanyInfoDTOs.length == 1) {
          this.user.userCompanyInfoDTOs[0].defaults = true;
        }
        // this.user.userCompanyInfoDTOs = this.user.userCompanyInfoDTOs.concat(items);
      }
      callback && callback();
    },
    deleteCompany(row, index) {
      let companyCode = row.companyCode;
      let companyDTO = this.getCompanyDTO(companyCode);
      this.user.userCompanyInfoDTOs.splice(index, 1);
      companyDTO.roleData = [];
      companyDTO.saleOrgData = [];
      this.user.userSaleOrgDTOs = this.user.userSaleOrgDTOs.filter(
        (item) => item.companyCode != companyCode
      );
      this.user.userRoleDTOs = this.user.userRoleDTOs.filter(
        (item) => item.companyCode != companyCode
      );
    },
    confirmInsertSaleOrg(rows) {
      if (rows.length > 0) {
        let companyCode = this.companyInfo.companyCode;
        let companyDTO = this.getCompanyDTO(companyCode);
        const $grid = this.$refs["saleOrgGrid-" + companyCode][0];
        const tableData = companyDTO.saleOrgData || [];
        const map = {};
        tableData.forEach(function (item) {
          map[item.saleOrgId] = 1;
        });

        let roleMap = {};
        let newUserRoleDTOs = [];
        var items = [];

        rows.forEach((row, index) => {
          const item = {
            companyCode: companyCode,
            companyName: row.companyName,
            defaults: false,
            saleOrgName: row.name,
            treePathName: row.treePathName,
            userSaleOrgPositionDTOs: [],
            saleOrgId: row.id,
            sn: row.sn,
          };

          if (!map[item.saleOrgId]) {
            items.push(item);
            if (row.roleId && !roleMap[row.roleId]) {
              const roleItem = {
                id: row.roleId,
                name: row.roleName,
                companyCode: companyCode,
                companyName: row.companyName,
              };
              roleMap[row.roleId] = true;
              newUserRoleDTOs.push(roleItem);
            }
          }
        });
        if (items.length > 0 && tableData.length == 0) {
          items[0].defaults = true;
        }

        companyDTO.saleOrgData.push(...items);
        this.confirmRole(newUserRoleDTOs);
      }
    },
    openSelectPositionDialog(row, rowIndex, $table) {
      const userSaleOrgPositionDTOs = row.userSaleOrgPositionDTOs || [];
      const items = [];
      userSaleOrgPositionDTOs.forEach((userSaleOrgPositionDTO) => {
        const item = {
          companyCode: userSaleOrgPositionDTO.companyCode,
          companyName: userSaleOrgPositionDTO.companyName,
          name: userSaleOrgPositionDTO.positionName,
          code: userSaleOrgPositionDTO.code,
          id: userSaleOrgPositionDTO.positionId,
        };
        items.push(item);
      });

      this.positionDialogDatas = items;
      this.saleOrgPositionIndex = rowIndex;
      this.showPositionDialog = true;
    },
    confirmInsertPosition(rows) {
      let companyCode = this.companyInfo.companyCode;
      const saleOrgPositionIndex = this.saleOrgPositionIndex;
      let companyDTO = this.getCompanyDTO(companyCode);
      const tableData = companyDTO.saleOrgData || [];
      if (rows.length > 0) {
        const oldPositions =
          tableData[saleOrgPositionIndex].userSaleOrgPositionDTOs || [];
        const map = {};
        oldPositions.forEach(function (item) {
          map[item.positionId] = item;
        });
        var oItems = [];
        var items = [];
        rows.forEach((row) => {
          const item = {
            companyCode: row.companyCode,
            companyName: row.companyName,
            positionName: row.name,
            code: row.code,
            positionId: row.id,
          };

          if (!map[item.positionId]) {
            items.push(item);
          } else {
            oItems.push(map[item.positionId]);
          }
        });
        tableData[saleOrgPositionIndex].userSaleOrgPositionDTOs =
          oItems.concat(items);
      } else {
        tableData[saleOrgPositionIndex].userSaleOrgPositionDTOs = [];
      }
      this.$forceUpdate();
    },
    getSelectPositionName(row) {
      var userSaleOrgPositions = row.userSaleOrgPositionDTOs || [];
      var allName = "";
      userSaleOrgPositions.forEach(function (pItem, pIndex) {
        allName = allName + "," + pItem.positionName;
      });
      if (allName) {
        allName = allName.substr(1);
      }
      return allName;
    },
    getConpanyInfo() {
      this.$http({
        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(() => {
              this.getUserRoleData();
              this.getSaleOrgData();
              setTimeout(() => {
                this.user.userCompanyInfoDTOs.forEach((userCompanyInfoDTO) => {
                  this.initSaleOrg(userCompanyInfoDTO.companyCode);
                  this.initUserRole(userCompanyInfoDTO.companyCode);
                });
              }, 100);
            });
          }
        },
      });
    },
    isCurrentCompany(companyCode) {
      return this.companyInfo.companyCode == companyCode;
    },
    addCurrentCompany(callback) {
      this.confirmInsertCompany([this.companyInfo], callback);
      setTimeout(() => {
        this.initSaleOrg(this.companyInfo.companyCode);
        this.initUserRole(this.companyInfo.companyCode);
        setTimeout(() => {
          if (this.userType === 2) {
            //经销商
            if (this.distributorRole) {
              this.confirmRole([this.distributorRole]);
            }
          }
        }, 100);
      }, 100);
    },
    handleData() {
      let saleOrgs = [];
      let roles = [];
      this.user.userCompanyInfoDTOs.forEach((companyDTO) => {
        saleOrgs.push(...companyDTO.saleOrgData);
        roles.push(...companyDTO.roleData);
      });

      this.user.userRoleDTOs = roles;
      this.user.userSaleOrgDTOs = saleOrgs;
    },
    initDistributorRole() {
      if (this.outUserCodes && this.outUserCodes.length == 1) {
        return this.$http({
          url: USER_PREFIX + "/role/list",
          method: "post",
          success: (res) => {
            let roleList = res.objx || [];
            let distributorCode = this.outUserCodes[0];
            this.distributorRole = roleList.find(
              (item) => item.code == distributorCode
            );
          },
        });
      }
    },
    async initOutUserRoleCode() {
      //初始化外部用户编码
      return this.$http({
        url: USER_PREFIX + "/system_parameter/getByCode",
        method: "post",
        data: { code: "outUserRoleCode" },
        success: (res) => {
          let value =
            !res.objx || !res.objx.value ? "distributor" : res.objx.value;
          let codes = value.split(",");
          this.outUserCodes = codes; //外部用户编码
          this.initRoleDialogParam(); //初始化角色弹框的查询参数
        },
      });
    },
    initRoleDialogParam() {
      //初始化角色弹框的查询参数
      if (this.userType == 1) {
        //组织用户
        this.roleDialogParam = {
          queryAll: true,
          neCodes: [...this.outUserCodes],
        };
      } else if (this.userType == 2) {
        //外部用户
        this.roleDialogParam = {
          queryAll: true,
          eqCodes: [...this.outUserCodes],
        };
      }
    },
    unlock() {
      this.$baseConfirm(this.$t1("您确定要解锁吗？")).then(() => {
        var url = USER_PREFIX + "/user/unlockLoginAccount";
        this.$http({
          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;
      }
    },
    changeCompanyDefault(item) {
      let companyCode = item.companyCode;
      if (item.defaults) {
        this.user.userCompanyInfoDTOs.forEach((row) => {
          row.defaults = row.companyCode == companyCode;
        });
      }
    },
    getCompanyDTO(companyCode) {
      return this.user.userCompanyInfoDTOs.find(
        (item) => item.companyCode == companyCode
      );
    },
    confirmArea(rows) {
      if (rows.length) {
        let row = rows[0];
        this.user.areaId = row.id;
        this.user.areaName = row.fullName;
      }
    },
  },
};
</script>
