<template>
  <div class="key-dm-user-wrapper">
    <Card>
      <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 type="primary" class="mr10" @click="handleSync">同步</Button>
            <Button @click="fetchList">刷新</Button>
          </Col>
          <Col :span="8" class="text-right">
            <span>姓名：</span>
            <Input v-model="filters.name" placeholder="请输入姓名" style="width: 40%" />
            <Button type="primary" class="mr10" @click="handleSearch">搜索</Button>
            <Button @click="handleReset">重置</Button>
          </Col>
        </Row>
      </div>

      <Table :data="rows" :loading="loading" border>
        <template slot="index" slot-scope="{ index }">
          <span>{{ index + 1 }}</span>
        </template>
        <TableColumn type="index" title="序号" width="60" align="center" />
        <TableColumn prop="name" title="姓名" align="center" />
        <TableColumn prop="gh" title="工号" align="center" />
        <TableColumn prop="office_name" title="归属部门" align="center" />
        <TableColumn prop="email" title="邮箱" align="center" />
        <TableColumn prop="phone" title="电话" align="center" />
        <TableColumn prop="mobile" title="手机" align="center" />
        <TableColumn prop="is_leave" title="离职" width="80" align="center" :render="renderIsLeave" />
        <TableColumn prop="is_ext" title="同步来源" width="120" align="center" :render="renderIsExt" />
        <TableColumn title="操作" width="200" align="center">
          <template slot-scope="{ row }">
            <Button size="small" type="primary" @click="openEdit(row)">修改</Button>
          </template>
        </TableColumn>
      </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" />
    </Card>

    <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,
      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 = { pageNo: this.pager.pageNo, pageSize: this.pager.pageSize, params: Object.assign({}, this.filters) }
      getDmUserList(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          const data = ret.data.data || {}
          this.rows = data.results || []
          this.pager.totalRecord = data.totalRecord || 0
        } 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; }
</style>
