<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.email" />
        </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="归属部门">
          <Input v-model="editModal.form.office_id" placeholder="请输入机构ID（可通过列表选择扩展）" />
        </FormItem>
        <FormItem label="直属领导ID">
          <Input v-model="editModal.form.leader" placeholder="只能选择本级或父机构人员ID" />
        </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',
  data () {
    return {
      officeCode: '',
      filters: { name: '' },
      rows: [],
      loading: false,
      columns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '姓名', key: 'name', align: 'center' },
        { title: '工号', key: 'gh', align: 'center' },
        { title: '归属部门', key: 'office_name', align: 'center' },
        { title: '邮箱', key: 'email', align: 'center' },
        { title: '电话', key: 'phone', align: 'center' },
        { title: '手机', key: 'mobile', align: 'center' },
        { title: '离职', key: 'is_leave', slot: 'is_leave', width: 80, align: 'center' },
        { title: '同步来源', key: 'is_ext', slot: 'is_ext', width: 120, align: 'center' },
        { title: '操作', slot: 'action', width: 200, align: 'center' }
      ],
      pager: { pageNo: 1, pageSize: 10, totalRecord: 0 },
      editModal: {
        visible: false,
        saving: false,
        form: {}
      }
    }
  },
  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 || []
          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) {
      this.editModal.form = Object.assign({}, row)
      this.editModal.visible = true
    },
    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>
