<template>
  <div class="key-dm-user-wrapper">
    <div class="search-div">
      <Row type="flex" :gutter="16" align="middle">
        <!-- <Col :span="8">
          <span>机构编码：</span>
          <Input v-model="officeCode" placeholder="请输入机构编码或留空为当前机构" style="width: 60%" />

          <Button @click="fetchList">刷新</Button>
        </Col> -->
        <Col :span="12" class="text-left">
          <span>姓名：</span>
          <Input v-model="filters.name" placeholder="请输入姓名" style="width: 200px" />
        </Col>
        <Col :span="12" class="text-right">
          <Button type="primary" class="mr10" @click="handleSearch">搜索</Button>
          <Button type="primary" @click="handleReset" class="mr10">重置</Button>
          <Button type="primary" class="mr10" @click="handleSync">同步</Button>
        </Col>
      </Row>
    </div>
      <Table border :loading="loading" :columns="columns" :data="rows">
        <template slot="is_leave" slot-scope="{ row }">
          <span>{{ renderIsLeave(null, { row }) }}</span>
        </template>
        <template slot="is_ext" slot-scope="{ row }">
          <span>{{ renderIsExt(null, { row }) }}</span>
        </template>
        <template slot="action" slot-scope="{ row }">
          <Button size="small" type="primary" @click="openEdit(row)">修改</Button>
        </template>
      </Table>
    <Page class="page_style" :total="pager.totalRecord" :current="pager.pageNo" :page-size="pager.pageSize"
      show-total show-sizer @on-change="pageChange" @on-page-size-change="sizeChange" />

    <Modal v-model="editModal.visible" title="编辑日常人员" width="700" :mask-closable="false">
      <Form :model="editModal.form" :label-width="120" ref="editForm">
        <FormItem label="姓名">
          <Input v-model="editModal.form.name" disabled />
        </FormItem>
        <FormItem label="工号">
          <Input v-model="editModal.form.gh" disabled />
        </FormItem>
        <FormItem label="电话">
          <Input v-model="editModal.form.phone" />
        </FormItem>
        <FormItem label="手机">
          <Input v-model="editModal.form.mobile" />
        </FormItem>
        <!-- <FormItem label="出生日期">
          <DatePicker v-model="editModal.form.birthday" type="date" placeholder="请选择日期" />
        </FormItem> -->
        <FormItem label="参加工作时间">
          <DatePicker v-model="editModal.form.in_work_time" type="date" placeholder="请选择日期" />
        </FormItem>
        <!-- 角色已移除 -->
        <!-- <FormItem label="归属部门">
          <SelectDisplay v-model="editModal.form.office_id" placeholder="请输入机构" @open="openOfficeSelect(editModal.form)" />
        </FormItem> -->
        <FormItem label="直属领导">
          <Input v-model="editModal.form.leader_name" readonly placeholder="点击选择直属领导" @click.native="selectLeader" style="cursor: pointer" />
        </FormItem>
        <FormItem label="是否离职">
          <Select v-model="editModal.form.is_leave" style="width: 160px" @on-change="onIsLeaveChange">
            <Option :value="0">未离职</Option>
            <Option :value="1">离职</Option>
          </Select>
        </FormItem>
        <FormItem v-if="editModal.form.is_leave === 1" label="离职时间">
          <DatePicker v-model="editModal.form.leave_time" type="date" placeholder="请选择离职时间" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="editModal.visible = false">取消</Button>
        <Button type="primary" :loading="editModal.saving" @click="saveEdit">保存</Button>
      </div>
    </Modal>

    <!-- 人员选择器 -->
    <UserSelector
      v-model="userSelectorVisible"
      permission=""
      @on-ok="handleLeaderSelected"
      @cancel="userSelectorVisible = false" />

    <!-- 领导与归属部门选择已移除 -->
  </div>
</template>

<script>
import { getDmUserList, syncDmUsersByOffice, saveDmUser } from '@/api/key-dm'
import UserSelector from './userSelector.vue'
import { normalizeVisitTimeValue } from '@/view/key-person/key_dm_conf/dates.js'

export default {
  name: 'key-dm-user-index',
  components: { UserSelector },
  data () {
    return {
      officeCode: '',
      filters: { name: '' },
      rows: [],
      // leaders/userTypes 已移除
      loading: false,
      columns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '姓名', key: 'name', align: 'center' },
        { title: '工号', key: 'gh', align: 'center' },
        { title: '电话', key: 'phone', align: 'center' },
        { title: '手机', key: 'mobile', align: 'center' },
        { title: '离职', key: 'is_leave', slot: 'is_leave', width: 80, align: 'center' },
        { title: '操作', slot: 'action', width: 200, align: 'center' }
      ],
      pager: { pageNo: 1, pageSize: 10, totalRecord: 0 },
      editModal: {
        visible: false,
        saving: false,
        form: {}
      },
      userSelectorVisible: false
      // leader / office state 已移除
    }
  },
  created () {
    this.fetchList()
  },
  methods: {
    renderIsLeave (h, { row }) {
      return row.is_leave === 1 ? '是' : '否'
    },
    renderIsExt (h, { row }) {
      return row.is_ext === 1 ? '系统同步' : '手工录入'
    },
    formatLeaveTime (leaveTime) {
      if (!leaveTime || leaveTime === null || leaveTime === '') return '-'
      // 如果是数字时间戳
      if (typeof leaveTime === 'number') {
        return this.formatDateTime(new Date(leaveTime))
      }
      // 如果是字符串
      if (typeof leaveTime === 'string') {
        // 处理纯数字字符串（可能是时间戳）
        if (/^\d+$/.test(leaveTime)) {
          try {
            return this.formatDateTime(new Date(Number(leaveTime)))
          } catch (e) {
            return leaveTime
          }
        }
        // 处理带T的ISO字符串或其他可解析字符串
        if (leaveTime.includes('T')) {
          return this.formatDateTime(leaveTime)
        }
        // 尝试直接解析
        const parsed = new Date(leaveTime)
        if (!isNaN(parsed.getTime())) {
          return this.formatDateTime(parsed)
        }
      }
      // 尝试解析为Date对象
      const parsed = new Date(leaveTime)
      if (!isNaN(parsed.getTime())) {
        return this.formatDateTime(parsed)
      }
      return leaveTime
    },
    formatDateTime (date) {
      if (!date) return '-'
      const d = date instanceof Date ? date : new Date(date)
      if (isNaN(d.getTime())) return '-'

      const pad = (n) => (n < 10 ? '0' + n : String(n))
      return d.getFullYear() + '-' +
             pad(d.getMonth() + 1) + '-' +
             pad(d.getDate()) + ' ' +
             pad(d.getHours()) + ':' +
             pad(d.getMinutes()) + ':' +
             pad(d.getSeconds())
    },
    fetchList () {
      this.loading = true
      const payload = Object.assign({}, { pageNo: this.pager.pageNo, pageSize: this.pager.pageSize }, this.filters)
      getDmUserList(payload).then(ret => {
        console.log('getDmUserList', ret)
        if (ret.data && ret.data.errcode === 0) {
          const data = ret.data.data || {}
          this.rows = (data.results || []).map(row => {
            // 规范化后端返回的大写 Id 到前端统一使用小写 id（作为主键）
            const copy = Object.assign({}, row)
            if (copy.Id != null && copy.id == null) copy.id = copy.Id
            // 处理嵌套对象可能带有 Id 的情况（归属机构/领导）
            if (copy.office_id && copy.office_id.Id != null && copy.office_id.id == null) {
              copy.office_id = Object.assign({}, copy.office_id, { id: copy.office_id.Id })
            }
            if (copy.leader && copy.leader.Id != null && copy.leader.id == null) {
              copy.leader = Object.assign({}, copy.leader, { id: copy.leader.Id })
            }
            return copy
          })
          this.pager.totalRecord = data.totalRecord || 0
          console.log('data', this.rows)
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data && ret.data.errmsg })
        }
      }).finally(() => { this.loading = false })
    },
    /* 用户角色加载已移除 */
    handleSearch () {
      this.pager.pageNo = 1
      this.fetchList()
    },
    handleReset () {
      this.filters = { name: '' }
      this.pager.pageNo = 1
      this.fetchList()
    },
    pageChange (pageNo) {
      this.pager.pageNo = pageNo
      this.fetchList()
    },
    sizeChange (size) {
      this.pager.pageSize = size
      this.pager.pageNo = 1
      this.fetchList()
    },
    handleSync () {
      const params = { office_code: this.officeCode }
      this.$Modal.confirm({
        title: '确认同步',
        content: '将同步本机构及下属机构的用户，已存在的记录会被更新，是否继续？',
        onOk: () => {
          this.loading = true
          syncDmUsersByOffice(params).then(ret => {
            if (ret.data && ret.data.errcode === 0) {
              this.$Message.success('同步完成')
              this.fetchList()
            } else {
              this.$Notice.error({ title: '同步失败', desc: ret.data && ret.data.errmsg })
            }
          }).finally(() => { this.loading = false })
        }
      })
    },
    openEdit (row) {
      // 直接拷贝记录用于编辑，并保证小写 id 可用
      const copy = Object.assign({}, row)
      if (copy.Id != null && copy.id == null) copy.id = copy.Id
      // 保存原始离职时间用于提交（保持后端原始格式），并将 leave_time 转为供前端显示的格式化字符串（disabled Input）
      copy._raw_leave_time = copy.leave_time
      copy.leave_time = this.formatLeaveTime(copy.leave_time)
      this.editModal.form = copy
      this.editModal.visible = true
    },
    selectLeader () {
      this.userSelectorVisible = true
    },
    onIsLeaveChange (value) {
      // 当切换为未离职，清理离职时间的显示与临时原始值，避免在提交时带上旧值
      if (value !== 1) {
        if (this.editModal && this.editModal.form) {
          // 保证字段存在再删除
          if (this.editModal.form.leave_time !== undefined) delete this.editModal.form.leave_time
          if (this.editModal.form._raw_leave_time !== undefined) delete this.editModal.form._raw_leave_time
        }
      }
    },
    handleLeaderSelected (user) {
      this.editModal.form.leader = user.id
      this.editModal.form.leader_name = user.name
      this.userSelectorVisible = false
    },
    /* leader / office 相关方法已移除 */
    saveEdit () {
      this.$refs.editForm.validate(valid => {
        // no strict validation here, just save
        const formData = Object.assign({}, this.editModal.form)
        // 如果当前为未离职状态，不提交离职时间字段
        if (formData.is_leave !== 1) {
          if (formData.leave_time !== undefined) delete formData.leave_time
          if (formData._raw_leave_time !== undefined) delete formData._raw_leave_time
        } else {
          // is_leave === 1 时按原逻辑处理离职时间
          if (formData._raw_leave_time !== undefined) {
            formData.leave_time = formData._raw_leave_time
          } else if (formData.leave_time && typeof formData.leave_time === 'string') {
            // 纯数字字符串（时间戳）
            if (/^\d+$/.test(formData.leave_time)) {
              formData.leave_time = Number(formData.leave_time)
            } else {
              // 尝试将常见格式 yyyy-MM-dd HH:mm:ss 转为 ISO 再解析
              const parsed = new Date(formData.leave_time.replace(' ', 'T'))
              if (!isNaN(parsed.getTime())) {
                formData.leave_time = parsed.getTime()
              }
            }
          } else if (formData.leave_time instanceof Date) {
            formData.leave_time = formData.leave_time.getTime()
          }
          // 清理临时字段
          if (formData._raw_leave_time !== undefined) delete formData._raw_leave_time
        }
        this.editModal.saving = true
        formData.in_work_time = formData.in_work_time ? normalizeVisitTimeValue(formData.in_work_time) : null
        formData.leave_time = formData.leave_time ? normalizeVisitTimeValue(formData.leave_time) : null
        saveDmUser(formData).then(ret => {
          if (ret.data && ret.data.errcode === 0) {
            this.$Message.success('保存成功')
            this.editModal.visible = false
            this.fetchList()
          } else {
            this.$Notice.error({ title: '保存失败', desc: ret.data && ret.data.errmsg })
          }
        }).finally(() => { this.editModal.saving = false })
      })
    }
  }
}
</script>

<style scoped>
.key-dm-user-wrapper { padding: 10px; }
.search-div { border: 1px solid #dce1e7; padding: 12px; margin-bottom: 12px; background-color: #f8fbff; }
.mr10 { margin-right: 10px; }
.page_style { margin-top: 12px; text-align: right; }
.text-left {
  text-align: left;
}
.text-right {
  text-align: right;
}
</style>
