<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: 40%" />
        </Col>
        <Col :span="12" class="text-right">
          <Button type="primary" class="mr10" @click="handleSearch">搜索</Button>
          <Button @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="直属领导">
          <SelectDisplay v-model="editModal.form.leader" placeholder="只能选择本级或父机构人员" @open="openSelectLeader(editModal.form)" />
        </FormItem> -->
        <FormItem label="是否离职">
          <Select v-model="editModal.form.is_leave" style="width: 160px">
            <Option :value="0">未离职</Option>
            <Option :value="1">离职</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="editModal.visible = false">取消</Button>
        <Button type="primary" :loading="editModal.saving" @click="saveEdit">保存</Button>
      </div>
    </Modal>
    <!-- 领导与归属部门选择已移除 -->
  </div>
</template>

<script>
import { getDmUserList, syncDmUsersByOffice, saveDmUser } from '@/api/key-dm-user'

export default {
  name: 'key-dm-user-index',
  components: {},
  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: {}
      },
      // leader / office state 已移除
    }
  },
  created () {
    this.fetchList()
  },
  methods: {
    renderIsLeave (h, { row }) {
      return row.is_leave === 1 ? '是' : '否'
    },
    renderIsExt (h, { row }) {
      return row.is_ext === 1 ? '系统同步' : '手工录入'
    },
    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: '将同步本机构及下属机构的用户，已存在的记录会被更新（不覆盖 null 值），是否继续？',
        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
      this.editModal.form = copy
      this.editModal.visible = true
    },
    /* leader / office 相关方法已移除 */
    saveEdit () {
      this.$refs.editForm.validate(valid => {
        // no strict validation here, just save
        this.editModal.saving = true
        saveDmUser(this.editModal.form).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>
