<template>
  <box-content>
    <div class="search" style="position: relative">
      <SearchForm size="mini" :that="this" :search-data="searchData" :search-form="searchForm"
        :search-handle="searchHandle" @search="handleSearch" @reset="handleReset" @new="handleAddUser"
        @group="hadleAddGroup" />
    </div>
    <base-table v-loading="loading" :columns="columns" :list="users" :search-data="searchData" :total="total"
      @getList="getList" @editCb="handleEditUser" @deleteCb="handleDeleteUser" @sortByColumn="sortByColumn">
      <!-- 选择自定义slot -->
      <template slot="tip-slot" slot-scope="{ scope }">
        <i v-if="
          diffTime(scope.row.LastLoginTime) >= 90 &&
          diffTime(scope.row.LastChangePassWordTime) >= 90
        " class="el-icon-warning" style="color: #f56c6c"
          :title="$t('system:userlist:tip:overTimeAndoverTimePassWord')" />
        <i v-else-if="diffTime(scope.row.LastLoginTime) >= 90" class="el-icon-warning" style="color: #f56c6c"
          :title="$t('system:userlist:tip:overTime')" />
        <i v-else-if="diffTime(scope.row.LastChangePassWordTime) >= 90" class="el-icon-warning" style="color: #f56c6c"
          :title="$t('system:userlist:tip:overTimePassWord')" />
      </template>
      <template slot="genderSlot" slot-scope="{ scope }">
        {{ scope.row.Sex ? 'Male' : 'Female' }}
      </template>
      <template slot="HospitalGroupListSlot" slot-scope="{ scope }">
        {{
          Array.isArray(scope.row.HospitalGroupList) &&
            scope.row.HospitalGroupList.length > 0
            ? scope.row.HospitalGroupList.map((item) => item.Name).join(', ')
            : ''
        }}
      </template>
      <template slot="UserTypeSlot" slot-scope="{ scope }">
        {{
          Array.isArray(scope.row.UserRoleList) &&
            scope.row.UserRoleList.length > 0
            ? scope.row.UserRoleList.filter((item) => !item.IsUserRoleDisabled)
              .map((item) => item.UserTypeShortName)
              .join(', ')
            : ''
        }}
      </template>
      <template slot="roleSlot" slot-scope="{ scope }">
        {{scope.row.RoleNameList.map((role) => role.RoleName).join(', ')}}
      </template>
      <template slot="isZhiZhunSlot" slot-scope="{ scope }">
        {{
          scope.row.IsZhiZhun
            ? $t('system:userlist:table:InternalOrExternal:Internal')
            : $t('system:userlist:table:InternalOrExternal:External')
        }}
      </template>
      <template slot="isTestUserSlot" slot-scope="{ scope }">
        {{
          scope.row.IsTestUser
            ? $t('system:userlist:table:IsTestUser:Yes')
            : $t('system:userlist:table:IsTestUser:No')
        }}
      </template>
      <template slot="statusSlot" slot-scope="{ scope }">
        {{
          scope.row.Status
            ? $t('system:userlist:table:Status:Enable')
            : $t('system:userlist:table:Status:Disable')
        }}
      </template>
    </base-table>
    <base-model v-if="config.visible" :config="config">
      <template slot="dialog-body">
        <el-form :inline="true" class="base-search-form">
          <el-form-item :label="$t('system:userlist:table:Email')">
            <el-input v-model="EMail" clearable />
          </el-form-item>
          <el-form-item :label="$t('system:userlist:table:Email')" v-show="false">
            <el-input v-model="EMail" />
          </el-form-item>
          <el-form-item>
            <!-- 查询 -->
            <el-button type="primary" icon="el-icon-search" @click="handleGroupSearch">
              {{ $t('common:button:search') }}
            </el-button>
            <!-- 重置 -->
            <el-button type="primary" icon="el-icon-refresh-left" @click="handleGroupReset">
              {{ $t('common:button:reset') }}
            </el-button>
          </el-form-item>
        </el-form>
        <el-form v-loading="groupLoading" size="small" :model="userInfo" label-width="80px" style="margin-top: 30px;"
          v-show="userInfo.Id">
          <el-form-item :label="$t('system:userlist:table:UserName')">
            <span>{{ userInfo.UserName }}</span>
          </el-form-item>
          <el-form-item :label="$t('system:userlist:table:LastName')">
            <span>{{ userInfo.LastName }}</span>
          </el-form-item>
          <el-form-item :label="$t('system:userlist:table:FirstName')">
            <span>{{ userInfo.FirstName }}</span>
          </el-form-item>
          <el-form-item :label="$t('system:userlist:table:Email')">
            <span>{{ userInfo.EMail }}</span>
          </el-form-item>
          <el-form-item :label="$t('system:userlist:table:Phone')">
            <span>{{ userInfo.Phone }}</span>
          </el-form-item>
          <el-form-item :label="$t('system:userlist:table:UserType')">
            <span>{{
              Array.isArray(userInfo.AccountList) ? userInfo.AccountList.map(item =>
                item.UserTypeShortName).join(",") : ''
            }}</span>
          </el-form-item>
          <el-form-item :label="$t('system:userlist:table:HospitalGroupIdList')">
            <el-select v-model="userInfo.HospitalGroupIdList" size="small" placeholder="Please select" multiple
              style="width: 100%">
              <template v-for="group of hospitalGroupList">
                <el-option :key="group.Id" :label="group.Name" :value="group.Id" />
              </template>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template slot="dialog-footer">
        <!-- 取消 -->
        <el-button size="small" type="primary" @click="config.visible = false">
          {{ $t("common:button:cancel") }}
        </el-button>
        <!-- 保存 -->
        <el-button size="small" type="primary" @click="addGroup" :loading="groupLoading" :disabled="!userInfo.Id">
          {{ $t("common:button:confirm") }}
        </el-button>
      </template>
    </base-model>
  </box-content>
</template>
<script>
import { getUserList, getUserTypeList, deleteSysUser, getHospitalGroupList, getUserByEmail, updateUserHospitalGroupInfo } from "@/api/admin";
// import { searchForm, searchHandle, columns } from './list'
import BoxContent from "@/components/BoxContent";
import SearchForm from "@/components/BaseForm/search-form";
import BaseTable from "@/components/BaseTable";
import tableMixins from "@/mixins/table";
import moment from 'moment'
import BaseModel from '@/components/BaseModel'
// 用户列表查询表单配置信息
// 用户列表查询表单事件配置信息
const searchDataDefault = () => {
  return {
    UserName: null,
    Phone: null,
    EMail: null,
    OrganizationName: null,
    UserState: null,
    UserType: null,
    PageIndex: 1,
    PageSize: 20,
    Asc: false,
    RealName: "",
    SortField: "CreateTime",
    CreateTimeArr: [],
    BeginCreateTime: null,
    EndCreateTime: null,
  };
};
export default {
  name: "UserList",
  components: { BoxContent, SearchForm, BaseTable, BaseModel },
  mixins: [tableMixins],
  data() {
    return {
      searchData: searchDataDefault(),
      config: {
        visible: false,
        title: this.$t('system:userlist:dialogTitle:addGroup'),
        width: '800px',
        appendToBody: true
      },
      EMail: '',
      userInfo: {},
      hospitalGroupList: [],
      groupLoading: false,
      columns: [
        { type: 'tip', slot: 'tip-slot' },
        { type: 'index' },
        {
          prop: 'UserCode',
          label: this.$t('system:userlist:table:S/N'),
          width: 100,
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        {
          prop: 'UserName',
          label: this.$t('system:userlist:table:UserName'),
          minWidth: 100,
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        {
          prop: 'FullName',
          label: this.$t('system:userlist:table:RealName'),
          minWidth: 120,
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        // {
        //   prop: 'Sex',
        //   label: this.$t('system:userlist:table:Gender'),
        //   hidden: true,
        //   slot: 'genderSlot',
        //   minWidth: 100,
        //   sortable: 'custom',
        //   showOverflowTooltip: true
        // },
        {
          prop: 'Phone',
          label: this.$t('system:userlist:table:Phone'),
          minWidth: 120,
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        {
          prop: 'EMail',
          label: this.$t('system:userlist:table:Email'),
          minWidth: 150,
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        {
          prop: 'OrganizationName',
          label: this.$t('system:userlist:table:Organization'),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: 'HospitalGroupId',
          label: this.$t('system:userlist:table:HospitalGroupList'),
          minWidth: 100,
          slot: 'HospitalGroupListSlot',
          // sortable: 'custom',
          showOverflowTooltip: true,
        },
        {
          prop: 'UserType',
          label: this.$t('system:userlist:table:UserType'),
          minWidth: 100,
          slot: 'UserTypeSlot',
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        {
          prop: 'IsZhiZhun',
          label: this.$t('system:userlist:table:InternalOrExternal'),
          hidden: true,
          slot: 'isZhiZhunSlot',
          minWidth: 140,
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        // {
        //   prop: 'IsTestUser',
        //   label: this.$t('system:userlist:table:IsTestUser'),
        //   hidden: true,
        //   slot: 'isTestUserSlot',
        //   minWidth: 120,
        //   sortable: 'custom',
        //   showOverflowTooltip: true,
        // },
        {
          prop: 'Status',
          label: this.$t('system:userlist:table:Status'),
          hidden: true,
          slot: 'statusSlot',
          minWidth: 100,
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        {
          prop: 'LastLoginTime',
          label: this.$t('system:userlist:table:LastLoginTime'),
          minWidth: 200,
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        {
          prop: 'LastChangePassWordTime',
          label: this.$t('system:userlist:table:LastChangePassWordTime'),
          minWidth: 250,
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        {
          prop: 'CreateTime',
          label: this.$t('system:userlist:table:createTime'),
          minWidth: 200,
          sortable: 'custom',
          showOverflowTooltip: true,
        },
        {
          type: 'operate',
          label: this.$t('common:action:action'),
          minWidth: 100,
          fixed: 'right',
          operates: [
            {
              name: this.$t('common:button:edit'),
              type: 'text',
              emitKey: 'editCb',
            },
            // {
            //   name: this.$t('common:button:delete'),
            //   type: 'danger',
            //   emitKey: 'deleteCb',
            // },
          ],
        },
      ],
      searchForm: [
        {
          type: 'Input',
          label: this.$t('system:userlist:label:UserName'),
          prop: 'UserName',
          width: '120px',
          placeholder: '',
        },
        {
          type: 'Input',
          label: this.$t('system:userlist:label:RealName'),
          prop: 'RealName',
          width: '120px',
          placeholder: '',
        },
        {
          type: 'Input',
          label: this.$t('system:userlist:label:Phone'),
          prop: 'Phone',
          width: '120px',
          placeholder: '',
        },
        {
          type: 'Input',
          label: this.$t('system:userlist:label:EMail'),
          prop: 'EMail',
          width: '120px',
          placeholder: '',
        },
        {
          type: 'Input',
          label: this.$t('system:userlist:label:Organization'),
          prop: 'OrganizationName',
          width: '120px',
          placeholder: '',
        },
        {
          type: 'Select',
          label: this.$t('system:userlist:label:InternalOrExternal'),
          prop: 'IsZhiZhun',
          width: '100px',
          options: [
            {
              label: this.$t(
                'system:userlist:label:InternalOrExternal:Internal'
              ),
              value: true,
            },
            {
              label: this.$t(
                'system:userlist:label:InternalOrExternal:External'
              ),
              value: false,
            },
          ],
          props: { label: 'label', value: 'value' },
          change: (scope) => '',
          placeholder: '',
        },
        // {
        //   type: 'Select',
        //   label: this.$t('system:userlist:label:IsTestUser'),
        //   prop: 'IsTestUser',
        //   width: '100px',
        //   options: [
        //     {
        //       label: this.$t('system:userlist:label:IsTestUser:Yes'),
        //       value: true,
        //     },
        //     {
        //       label: this.$t('system:userlist:label:IsTestUser:No'),
        //       value: false,
        //     },
        //   ],
        //   props: { label: 'label', value: 'value' },
        //   change: (scope) => '',
        //   placeholder: '',
        // },
        {
          type: 'Select',
          label: this.$t('system:userlist:label:Status'),
          prop: 'UserState',
          width: '100px',
          options: [
            { label: this.$t('system:userlist:label:Status:Enable'), value: 1 },
            {
              label: this.$t('system:userlist:label:Status:Disable'),
              value: 0,
            },
          ],
          props: { label: 'label', value: 'value' },
          change: (scope) => '',
          placeholder: '',
        },
        {
          type: 'Select',
          label: this.$t('system:userlist:label:HospitalGroupList'),
          prop: 'HospitalGroupId',
          width: '100px',
          options: [], // 下拉选项
          props: { label: 'Name', value: 'Id' }, // 下拉选项配置信息，必填
          placeholder: '',
        },
        {
          type: 'Select',
          label: this.$t('system:userlist:label:UserType'),
          prop: 'UserType',
          width: '100px',
          options: [], // 下拉选项
          props: { label: 'UserType', value: 'Id' }, // 下拉选项配置信息，必填
          placeholder: '',
        },
        {
          type: 'Daterange',
          label: this.$t('system:userlist:label:LastLoginTime'),
          prop: 'LastLoginTimeArr',
          width: '400px',
          placeholder: '',
        },
        {
          type: 'Daterange',
          label: this.$t('system:userlist:label:LastChangePassWordTime'),
          prop: 'LastChangePassWordTimeArr',
          width: '400px',
          placeholder: '',
        },
        {
          type: 'Daterange',
          label: this.$t('system:userlist:label:CreateTime'),
          prop: 'CreateTimeArr',
          width: '400px',
          placeholder: '',
        },
      ],
      searchHandle: [
        {
          label: this.$t('common:button:search'),
          type: 'primary',
          emitKey: 'search',
          icon: 'el-icon-search',
        },
        {
          label: this.$t('common:button:reset'),
          type: 'primary',
          emitKey: 'reset',
          icon: 'el-icon-refresh-left',
        },
        {
          label: this.$t('common:button:new'),
          type: 'primary',
          emitKey: 'new',
        },
        {
          label: this.$t('system:userlist:button:addGroup'),
          type: 'primary',
          emitKey: 'group',
        },
      ],
      userTypeOptions: [],
      loading: false,
      total: 0,
      users: [],
    };
  },
  created() {
    this.getList();
    this.getInfo();
    this.getHospitalGroupList()
  },
  methods: {
    async addGroup() {
      try {
        let HospitalGroupList = []
        if (Array.isArray(this.userInfo.HospitalGroupIdList) && this.userInfo.HospitalGroupIdList.length > 0) {
          this.hospitalGroupList.forEach(item => {
            if (this.userInfo.HospitalGroupIdList.includes(item.Id)) {
              HospitalGroupList.push({
                HospitalGroupId: item.Id,
                IsDisabled: false
              })
            }
          })
        }
        let data = {
          Id: this.userInfo.Id,
          HospitalGroupList: HospitalGroupList,
        }
        this.groupLoading = true
        let res = await updateUserHospitalGroupInfo(data)
        this.groupLoading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:updatedSuccessfully'))
          this.config.visible = false
          this.getList()
        }
      } catch (err) {
        this.groupLoading = false
        console.log(err)
      }
    },
    async handleGroupSearch() {
      try {
        let params = {
          EMail: this.EMail,
          PageSize: 1000,
          PageIndex: 1,
        }
        this.userInfo = {}
        this.groupLoading = true
        let res = await getUserByEmail(params)
        this.groupLoading = false
        if (res.IsSuccess) {
          this.userInfo = res.Result || {}
          this.userInfo.HospitalGroupIdList = []
        }
      } catch (err) {
        this.groupLoading = false
        console.log(err)
      }
    },
    handleGroupReset() {
      this.EMail = ''
      this.handleGroupSearch()
    },
    hadleAddGroup() {
      this.userInfo = {}
      this.EMail = ''
      this.config.visible = true
    },
    diffTime(time) {
      return moment(new Date()).diff(time, 'days')
    },
    async getHospitalGroupList() {
      try {
        let res = await getHospitalGroupList({})
        if (res.IsSuccess) {
          this.hospitalGroupList = res.Result
          const index = this.findItemIndex("HospitalGroupId");
          this.$set(this.searchForm[index], "options", this.hospitalGroupList);
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取用户信息
    getList() {
      this.loading = true;
      if (
        this.searchData.CreateTimeArr[0] &&
        this.searchData.CreateTimeArr[1]
      ) {
        this.searchData.BeginCreateTime =
          this.searchData.CreateTimeArr[0];
        this.searchData.EndCreateTime =
          this.searchData.CreateTimeArr[1];
      } else {
        this.searchData.BeginCreateTime = null;
        this.searchData.EndCreateTime = null;
      }
      getUserList(this.searchData)
        .then((res) => {
          this.loading = false;
          this.users = res.Result.CurrentPageData;
          this.total = res.Result.TotalCount;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    findItemIndex(key) {
      return this.searchForm.findIndex(
        (value) => value.prop && value.prop === key
      );
    },
    // 获取用户类型下拉选项信息
    async getInfo() {
      const res = await getUserTypeList();
      let arr = [];
      if (this.hasPermi(["role:admin"])) {
        arr = [1];
      }
      if (this.hasPermi(["role:sa"])) {
        arr = [1, 2];
      }
      if (this.hasPermi(["role:pm"])) {
        arr = [1, 2, 14];
      }
      let roleList = res.Result.map((item) => {
        if (!arr.includes(item.UserTypeEnum)) {
          return item;
        }
      }).filter((item) => item);
      const index = this.findItemIndex("UserType");
      this.$set(this.searchForm[index], "options", roleList);
    },
    handleAddUser() {
      this.$router.push({ path: "/system/user/add" });
    },
    // 编辑用户
    handleEditUser(data) {
      this.$router.push({
        path: "/system/user/edit",
        query: { Id: data.Id, userName: data.UserName, email: data.EMail },
      });
    },
    // 删除用户
    handleDeleteUser(data) {
      this.$confirm(this.$t("trials:uploadedDicoms:message:deleteMes"), {
        type: "warning",
        distinguishCancelAndClose: true,
      }).then(() => {
        deleteSysUser(data.Id).then((res) => {
          if (res.IsSuccess) {
            this.users.splice(
              this.users.findIndex((item) => item.Id === data.Id),
              1
            );
            this.$message.success(
              this.$t("common:message:deletedSuccessfully")
            );
          }
        });
      });
    },
    // 重置列表查询
    handleReset() {
      this.searchData = searchDataDefault();
      this.getList();
    },
  },
};
</script>
<style scoped lang="scss">
/deep/ .box-body .search .base-search-form .el-form-item {
  margin-bottom: 15px;
}
</style>
