<template>
  <div :class="$style['address']">
    <template v-if="treeId">
      <div :class="$style['search']">
        <a-input-group compact>
          <a-select v-model="searchType" @change="searchTypeChange">
            <a-select-option value="0">
              按姓名
            </a-select-option>
            <a-select-option value="1">
              按拼音
            </a-select-option>
            <a-select-option value="2">
              按手机
            </a-select-option>
            <a-select-option value="4">
              按邮箱
            </a-select-option>
          </a-select>
          <a-input-search
            v-model="searchValue"
            placeholder="请输入搜索条件"
            allow-clear
            @search="onSearch"
          />
        </a-input-group>
      </div>
      <div :class="$style['list']">
        <ul>
          <span>按字母检索：</span>
          <li v-for="(item, index) in listData" :key="index">
            <span
              :class="currentIndex === index ? $style['selected'] : ''"
              @click="letterClick(item, index)"
            >
              {{ item }}
            </span>
          </li>
          <li><span @click="showAll">显示全部</span></li>
        </ul>
      </div>
      <sd-data-table-ex
        ref="dataTable"
        :key="treeId"
        :data-url="`api/framework/v1/oa-base-address-user/${treeId}/members`"
        :columns="columns"
        :form-id="formId"
        :page-id="pageId"
        :actions="computedActions"
        :modal-props="{ class: $style.modalstyle }"
        :show-selection="
          (record) => {
            // 只有部分行有复选框
            return record.isCanDel === 1
          }
        "
        :filter-expressions="computedExpressions"
        @formBtnClick="formBtnClick"
      >
        <template slot="bt" slot-scope="text, record">
          <sd-company-address-avatar
            :key="record.avatraId"
            :record="record"
            :permission="canEditAvatar"
            @updateTable="updateTable"
            @showDetail="showDetail"
          />
        </template>

        <template slot="post" slot-scope="text">
          {{ text && JSON.parse(text)[0] ? JSON.parse(text)[0].name : '' }}
        </template>

        <template v-slot:form="scope">
          <table id="table" :class="$style['table']">
            <colgroup>
              <col :class="$style.label" />
              <col :class="$style.input" />
              <col :class="$style.label" />
              <col :class="$style.input" />
            </colgroup>
            <tr>
              <td :colspan="4" :class="$style['info']"><div>工作信息</div></td>
            </tr>
            <tr>
              <td :colspan="4">
                <sd-upload-avatar
                  :userinfo-account="scope.model.account"
                  :userinfo-avatar="scope.model.avatraId"
                  :record-id="scope.model.id"
                  :permission="canEditAvatar"
                  @uploadAvatar="uploadAvatar"
                ></sd-upload-avatar>
              </td>
            </tr>
            <tr>
              <!-- 姓名 -->
              <sd-form-item-td name="name"></sd-form-item-td>
              <!-- 性别 -->
              <sd-form-item-td name="sex"></sd-form-item-td>
            </tr>
            <tr v-if="scope.model.isCanDel === 0">
              <!-- 账号 -->
              <sd-form-item-td name="account"></sd-form-item-td>
              <!-- 工号 -->
              <sd-form-item-td name="jobNumber"></sd-form-item-td>
            </tr>
            <tr>
              <!-- 所在部门 -->
              <sd-form-item-td
                name="department"
                :input-props="{ defaultValue: selectedNode.name, disabled: true }"
              ></sd-form-item-td>
              <!-- 所在部门ID -->
              <sd-form-item-td
                name="departmentId"
                :input-props="{ defaultValue: Number(selectedNode.id) }"
                :hidden="true"
              ></sd-form-item-td>
              <!-- 所在部门编码 -->
              <sd-form-item-td
                name="departmentCode"
                :input-props="{ defaultValue: selectedNode.props.code }"
                :hidden="true"
              ></sd-form-item-td>
              <!-- 兼职部门 -->
              <sd-form-item-td name="jobDepartment"></sd-form-item-td>
            </tr>
            <tr>
              <!-- 座机 -->
              <sd-form-item-td name="tel"></sd-form-item-td>
              <!-- 邮箱 -->
              <sd-form-item-td name="email"></sd-form-item-td>
            </tr>
            <tr>
              <!-- 手机 -->
              <sd-form-item-td
                name="phone"
                :colspan="scope.pageId === 'base/address/oaBaseAddressUserView' ? 3 : 1"
              >
                <template v-slot:read>
                  <span v-if="scope.model.phoneIsOpen === '0'">不公开</span>
                </template>
              </sd-form-item-td>
              <!-- 手机是否公开 -->
              <sd-form-item-td
                name="phoneIsOpen"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              >
                <a-switch
                  :checked="scope.model.phoneIsOpen === '1' ? true : false"
                  @change="switchChange('phoneIsOpen', $event)"
                />
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 职务 -->
              <sd-form-item-td
                name="post"
                :colspan="scope.pageId === 'base/address/oaBaseAddressUserView' ? 3 : 1"
              >
                <template>
                  <sd-select v-model="scope.model.post" :options="jobOptions" allow-clear />
                </template>
                <template v-slot:read>
                  <span v-if="scope.model.postIsOpen === '0'">不公开</span>
                  <span v-else>
                    <sd-select v-model="scope.model.post" :options="jobOptions" :read-only="true" />
                  </span>
                </template>
              </sd-form-item-td>
              <!-- 职务是否公开 -->
              <sd-form-item-td
                name="postIsOpen"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              >
                <a-switch
                  :checked="scope.model.postIsOpen === '1' ? true : false"
                  @change="switchChange('postIsOpen', $event)"
                />
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 现任职级 -->
              <sd-form-item-td
                name="curentRank"
                :colspan="scope.pageId === 'base/address/oaBaseAddressUserView' ? 3 : 1"
              >
                <template v-slot:read>
                  <span v-if="scope.model.curentRankIsOpen === '0'">不公开</span>
                </template>
              </sd-form-item-td>
              <!-- 现任职级是否公开 -->
              <sd-form-item-td
                name="curentRankIsOpen"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              >
                <a-switch
                  :checked="scope.model.curentRankIsOpen === '1' ? true : false"
                  @change="switchChange('curentRankIsOpen', $event)"
                />
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 资格名称 -->
              <sd-form-item-td
                name="qualificationName"
                :colspan="scope.pageId === 'base/address/oaBaseAddressUserView' ? 3 : 1"
              >
                <template v-slot:read>
                  <span v-if="scope.model.qualificationNameIsOpen === '0'">不公开</span>
                </template>
              </sd-form-item-td>
              <!-- 资格名称是否公开 -->
              <sd-form-item-td
                name="qualificationNameIsOpen"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              >
                <a-switch
                  :checked="scope.model.qualificationNameIsOpen === '1' ? true : false"
                  @change="switchChange('qualificationNameIsOpen', $event)"
                />
              </sd-form-item-td>
            </tr>
            <tr v-if="scope.pageId === 'base/address/oaBaseAddressUser'">
              <td :colspan="4" :class="$style['info']"><div>个人信息</div></td>
            </tr>
            <tr>
              <!-- 民族 -->
              <sd-form-item-td
                name="nation"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              ></sd-form-item-td>
              <!-- 出生年月 -->
              <sd-form-item-td
                name="dateOfBirth"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              ></sd-form-item-td>
            </tr>
            <tr>
              <!-- 籍贯 -->
              <sd-form-item-td
                name="nativePlace"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              ></sd-form-item-td>
              <!-- 身份证号
              <sd-form-item-td
                name="idNumber"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              ></sd-form-item-td>
              -->
            </tr>
            <tr>
              <!-- 政治面貌 -->
              <sd-form-item-td
                name="politicalOutlook"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              ></sd-form-item-td>
              <!-- 文化程度 -->
              <sd-form-item-td
                name="degreeOfEducation"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              ></sd-form-item-td>
            </tr>
            <tr>
              <!-- 员工入职时间 -->
              <sd-form-item-td
                name="employeeEntryTime"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              ></sd-form-item-td>
              <!-- 参加工作时间 -->
              <sd-form-item-td
                name="workingHours"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              ></sd-form-item-td>
            </tr>
            <tr
              v-if="scope.pageId === 'base/address/oaBaseAddressUser'"
              :hidden="scope.fields.isDispaly.readonly"
            >
              <td :colspan="4" :class="$style['info']"><div>显示信息</div></td>
            </tr>
            <tr :hidden="scope.fields.isDispaly.readonly">
              <!-- 通讯录中是否显示 -->
              <sd-form-item-td
                name="isDispaly"
                :colspan="3"
                :hidden="scope.pageId === 'base/address/oaBaseAddressUserView'"
              >
                <a-switch
                  :checked="scope.model.isDispaly === '1' ? true : false"
                  @change="switchChange('isDispaly', $event)"
                />
              </sd-form-item-td>
            </tr>
          </table>
        </template>
      </sd-data-table-ex>
      <a-modal
        v-model="visible"
        :mask-closable="false"
        title="导入用户信息"
        destroy-on-close
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-radio-group v-model="typeValue">
          <a-radio :style="radioStyle" :value="1">
            导入系统用户基本信息
          </a-radio>
          <a-radio :style="radioStyle" :value="2">
            导入非系统用户基本信息
          </a-radio>
        </a-radio-group>
        <div :class="$style['attach']">
          <sd-attachment v-model="files" :max="1" :group-id="groupId" accept=".xls,.xlsx" />
        </div>
        <span v-if="typeValue">模板下载：</span>
        <a-button v-if="typeValue === 1" type="link" @click="oaExport">
          系统用户基本信息导入模板.xls
        </a-button>
        <a-button v-if="typeValue === 2" type="link" @click="notOaExport">
          非系统用户基本信息导入模板.xls
        </a-button>
      </a-modal>
    </template>
  </div>
</template>

<script>
import storeMixin from '@/common/store-mixin'
import download from '@/common/services/download'
import { Message, Modal } from 'ant-design-vue'
import TableActionTypes from '@/common/services/table-action-types'
import AddressbookService from './addressbook-service'
import components from './_import-components/sd-company-address-list-import'
const listData = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z',
]
export default {
  name: 'SdCompanyAddressList',
  metaInfo: {
    title: '单位通讯录',
  },
  inject: ['SdTabbedView'],
  components,
  mixins: [storeMixin],
  props: {
    treeId: {
      type: String,
      default: '',
    },
    // 是否包含子部门
    isContainSubOrg: {
      type: Boolean,
      default: false,
    },
    selectedNode: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      listData,
      currentIndex: '',
      groupId: '',
      initials: '',
      avatarParam: null,
      formId: 'oaBaseAddressUser',
      pageId: 'base/address/oaBaseAddressUser',

      files: [],
      visible: false,
      typeValue: 1,
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
        width: '100%',
      },

      nodePerms: {},

      columns: [
        {
          title: '姓名',
          dataIndex: 'name',
          width: '200px',
          scopedSlots: { customRender: 'bt' },
        },
        {
          title: '手机',
          dataIndex: 'phone',
        },
        {
          title: '座机电话',
          dataIndex: 'tel',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
        },
        {
          title: '职务',
          dataIndex: 'post',
          scopedSlots: { customRender: 'post' },
        },
      ],

      searchType: '0',
      searchValue: '',
      searchExpressions: [],
      jobOptions: [],
    }
  },
  computed: {
    computedExpressions() {
      const expressions = [
        {
          name: 'isContainsSub',
          stringValue: this.isContainSubOrg ? 'y' : 'n',
        },
        {
          name: 'initials',
          stringValue: this.initials,
        },
      ]

      return [...expressions, ...this.searchExpressions]
    },

    computedActions() {
      const actions = [
        {
          label: '初始化数据',
          id: 'init',
          permission: 'oaBaseAddressUnit-syn',
          callback: this.fnInit,
        },
      ]

      if (this.nodePerms.create === 'true') {
        actions.push({
          label: '新建组织',
          permission: null,

          id: 'newGroup',
          callback: () => {
            this.$emit('newGroup')
          },
        })
      }

      if (this.nodePerms.edit === 'true') {
        actions.push({
          label: '编辑组织',
          permission: null,
          id: 'editGroup',
          callback: () => {
            this.$emit('editGroup')
          },
        })
      }

      if (this.nodePerms.delete === 'true') {
        actions.push({
          label: '删除组织',
          permission: null,
          id: 'deleteGroup',
          callback: () => {
            this.$emit('deleteGroup')
          },
        })
      }

      if (this.nodePerms.createPerson === 'true') {
        actions.push(
          {
            label: '新建非系统用户',
            permission: null,
            type: 'primary',
            id: 'new',
            callback: () => {
              this.$refs.dataTable.showDetailModal(null, this.pageId)
            },
          },
          {
            label: '删除用户',
            id: 'delete',
            type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
          }
        )
      }

      if (this.nodePerms.import === 'true') {
        actions.push({
          label: '导入',
          permission: null,
          id: 'import',
          callback: () => {
            AddressbookService.getGroupCode().then((res) => {
              if (res.status === 200) {
                if (res.data) {
                  this.groupId = res.data.toString()
                  this.visible = true // 弹出导入面板
                } else {
                  Message.error('获取groupId失败')
                }
              } else {
                Message.error(res.statusText)
              }
            })
          },
        })
      }

      if (this.nodePerms.export === 'true') {
        actions.push({
          label: '导出',
          id: 'export',
          permission: null,
          callback: (keys) => {
            const url = `api/framework/v1/oa-base-address-user/export-excel?parentId=${this.treeId}&isContainSubOrg=${this.isContainSubOrg}`
            const fname = '单位通讯录.xls'
            download(url, fname)
          },
        })
      }

      return actions
    },

    // 能否编辑头像
    canEditAvatar() {
      return this.nodePerms.createPerson === 'true'
    },
  },
  watch: {
    treeId(value) {
      this.getNodeProps(value)
    },
  },
  created() {
    this.getJobOptions()
  },
  methods: {
    // 获取选中节点相关的按钮权限
    getNodeProps(treeId) {
      if (treeId) {
        this.nodePerms = {}
        AddressbookService.getNodeProps(treeId).then((res) => {
          this.nodePerms = res.data
        })
      }
    },
    switchChange(name, checked) {
      this.$refs.dataTable.getDetailModal().setFieldValue(name, checked ? '1' : '0')
    },
    letterClick(val, index) {
      this.currentIndex = index
      this.initials = val
    },
    showAll() {
      this.currentIndex = ''
      this.initials = ''
    },
    updateTable() {
      this.$refs.dataTable.refresh()
    },
    showDetail(currentData) {
      this.$refs.dataTable.showDetailModal(currentData.recordId, currentData.pageId)
    },

    // 搜索的类型变化时
    searchTypeChange() {
      this.searchValue = ''
      this.onSearch()
    },

    // 搜索
    onSearch(value) {
      if (value) {
        let name = ''
        switch (this.searchType) {
          case '0':
            name = 'name'
            break
          case '1':
            name = 'pinYin'
            break
          case '2':
            name = 'phone'
            break
          case '3':
            name = 'jobNumber'
            break
          case '4':
            name = 'email'
            break
          default:
            name = 'name'
            break
        }

        this.searchExpressions = [
          {
            dataType: 'exps',
            op: 'or',
            expressionsValue: [
              {
                dataType: 'str',
                name,
                op: 'like',
                stringValue: `%${value}%`,
              },
            ],
          },
        ]
      } else {
        this.searchExpressions = []
      }
    },

    handleOk(e) {
      if (this.files.length === 0) {
        Message.error('请上传文件')
      } else {
        if (this.typeValue === 1) {
          AddressbookService.oaImport(this.files[0])
            .then((res) => {
              if (res.data.errorDataList && res.data.errorDataList.length > 0) {
                Modal.confirm({
                  title: '导入出错',
                  content: `有部分数据导入失败，点击“确定”按钮下载导入失败的数据。`,
                  onOk: () => {
                    // 下载导入失败的数据
                    const url = `api/framework/v1/oa-base-address-user/OA/export-error`
                    const fname = '系统用户导入错误信息.xls'
                    download({ url, method: 'post', data: res.data }, fname)
                  },
                  onCancel: () => {},
                })
              } else {
                Message.success(`导入成功：${res.data.count}条`)
                this.updateTable()
              }
              this.visible = false
            })
            .catch((err) => {
              Message.error(err)
            })
        } else {
          AddressbookService.notOaImport(this.files[0])
            .then((res) => {
              if (res.data.errorDataList && res.data.errorDataList.length > 0) {
                Modal.confirm({
                  title: '导入出错',
                  content: `有部分数据导入失败，点击“确定”按钮下载导入失败的数据。`,
                  onOk: () => {
                    // 下载导入失败的数据
                    const url = `api/framework/v1/oa-base-address-user/not-OA/export-error`
                    const fname = '非系统用户导入错误信息.xls'
                    download({ url, method: 'post', data: res.data }, fname)
                  },
                  onCancel: () => {},
                })
              } else {
                Message.success(`导入成功：${res.data.count}条`)
                this.updateTable()
              }
              this.visible = false
            })
            .catch((err) => {
              Message.error(err)
            })
        }
      }
    },
    handleCancel(e) {
      this.visible = false
    },
    oaExport() {
      // OA用户通讯录全局导出模板
      const url = `api/framework/v1/oa-base-address-user/OA/export-excel?parentId=${this.treeId}&isContainSubOrg=${this.isContainSubOrg}`
      const fname = '系统用户基本信息导入模板.xls'
      download(url, fname)
    },
    notOaExport(values) {
      // 非OA用户通讯录全局导出模板
      const url = 'api/framework/v1/oa-base-address-user/not-OA/export-excel'
      const fname = '非系统用户基本信息导入模板.xls'
      download(url, fname)
    },

    uploadAvatar(param) {
      this.avatarParam = param
    },
    formBtnClick(evt, btn, { form, recordId }) {
      if (btn.buttonId === 'save') {
        evt.waitUntil(
          new Promise((resolve, reject) => {
            evt.preventDefault()
            form
              .validateFields()
              .then(() => {
                form
                  .save()
                  .then((res) => {
                    if (this.avatarParam) {
                      if (!this.avatarParam.userAccount) {
                        this.avatarParam.userAccount = res.data.pageFormData.beanId
                      }
                      AddressbookService.uploadAvatar(this.avatarParam)
                        .then((res) => {
                          form.hide()
                          resolve()
                          if (res && res.data) {
                            this.avatarParam = null // 清空历史头像数据
                            this.updateTable()
                          }
                        })
                        .catch((e) => {
                          form.hide()
                          resolve()
                          this.avatarParam = null // 清空历史头像数据
                          Message.error('头像保存失败')
                        })
                    } else {
                      form.hide()
                      this.updateTable()
                    }
                  })
                  .catch(() => {
                    resolve()
                  })
              })
              .catch(() => {
                resolve()
              })
          })
        )
      }
    },

    // 初始化
    fnInit() {
      return AddressbookService.initialization().then(() => {
        this.SdTabbedView.reload()
      })
    },

    // 获取后台职务配置
    getJobOptions() {
      AddressbookService.getJobOptions().then((res) => {
        this.jobOptions = res.data.map((item) => {
          return {
            id: item.id,
            code: item.code,
            name: item.name,
          }
        })
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
$font-size-md: 16px;
.modalstyle {
  :global(.ant-form-item) {
    margin: 12px;
  }
  :global(#table) {
    :global(.ant-form-item-label:not(.sd-readonly)) {
      padding-bottom: 0;
    }
  }
}
.bt {
  cursor: pointer;
  &:hover {
    color: $primary-color;
  }
}
.address {
  position: relative;
  :global(.ant-table) {
    max-height: calc(100vh - 330px);
    margin-top: 90px;
    overflow-x: hidden;
    overflow-y: auto;
  }
}
.table {
  .label {
    width: 20%;
  }
  .input {
    width: 30%;
  }
  tr {
    border: 1px solid #e8e8e8;
  }
  .info {
    background-color: $background-color-light;
    div {
      margin: 10px;
      font-weight: bold;
    }
  }
}
.errorinfo {
  ul {
    padding: 0;
    margin: 0;
    list-style-type: none;
  }
}
.list {
  position: absolute;
  top: 55px;
  z-index: 1;
  font-size: $font-size-md;
  font-weight: 600;
  list-style-type: none;
  ul {
    padding: 0;
    margin: 0;
  }
  li {
    display: inline-block;
    margin: 0 4px;
    span {
      cursor: pointer;
      &:hover {
        color: $primary-color;
      }
    }
  }
}
.search {
  position: absolute;
  top: 52px;
  right: 0;
  :global(.ant-input-search) {
    width: 160px;
  }
}
.selected {
  color: $highlight-color;
}
.attach {
  margin: 20px 0;
}
</style>
