<template>
  <div>
    <card-container>
      <vxe-toolbar print custom export>
        <template #buttons>
          <el-select v-model="select.user_id" size="small" style="width: 160px;">
            <el-option v-for="item in users" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-date-picker
            v-model="select.month"
            type="month"
            size="small"
            value-format="yyyy-MM"
            style="width: 160px;margin-left: 10px;">
          </el-date-picker>
          <el-button icon="el-icon-search" type="primary" plain size="small" style="margin-left: 10px;" @click="getList">搜索</el-button>
          <el-button icon="el-icon-plus" type="primary" size="small" style="margin-left: 10px;" @click="isShowAdd = true">补卡</el-button>
          <el-popover
            placement="bottom-start"
            title="导入"
            width="400"
            trigger="click">
            <template #reference>
              <el-button style="margin-left: 10px;" type="primary" size="small" icon="el-icon-upload">导入</el-button>
            </template>
            <template #default>
              <el-upload
                ref="upload"
                :action="action"
                :on-success="uploadSuccess"
                accept=".xls,.xlsx"
                :headers="{
                      'Authorization': 'Bearer ' + getToken()
                    }"
                :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="uploadData">上传到服务器</el-button>
                <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
              </el-upload>
            </template>
          </el-popover>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="table"
        stripe
        style="margin-top: 10px;"
        :loading="loading"
        keep-source
        show-overflow
        :max-height="1400"
        :min-height="400"
        :export-config="{}"
        :print-config="{}"
        :edit-config="{ trigger: 'manual', mode: 'row', showStatus: true, autoClear: false, expandALl: true }"
        align="center"
        :column-config="{ resizable: true }"
        :data="tableData"
      >
        <vxe-column type="seq" width="58" align="center" />
        <vxe-column width="120" field="date" title="日期" align="center" />
        <vxe-column field="attendance.sign_in_at" title="签到时间" width="200" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker style="width: 100%;" v-model="row.attendance.sign_in_at" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" size="small"></el-date-picker>
          </template>
        </vxe-column>
        <vxe-column field="attendance.sign_in_at_address" title="签到地址" width="140" :edit-render="{ name: 'input' }"></vxe-column>
        <vxe-column field="attendance.sign_in_at_location" title="签到坐标" width="140" :edit-render="{ name: 'input' }"></vxe-column>

        <vxe-column field="attendance.sign_out_at" title="签退时间" width="200" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker style="width: 100%;" v-model="row.attendance.sign_out_at" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" size="small"></el-date-picker>
          </template>
        </vxe-column>
        <vxe-column field="attendance.sign_out_at_address" title="签退地址" width="140" :edit-render="{ name: 'input' }"></vxe-column>
        <vxe-column field="attendance.sign_out_at_location" title="签退坐标" width="140" :edit-render="{ name: 'input' }"></vxe-column>
        <vxe-column field="attendance.status" title="类型" width="140" :edit-render="{ name: 'select', options: [{ label: '-',value: ''},{ label: '正常',value: 1},{ label: '补卡',value: 2},{ label: '外勤',value: 3}] }" />

        <vxe-column fixed="right" field="operate" title="操作" min-width="160" header-align="center" align="left">
          <template #default="{ row }">
            <template v-if="isActiveStatus(row)">
              <el-button size="small" type="primary" @click="saveRowEvent(row)">保存</el-button>
              <el-button size="small" type="primary" plain @click="cancelRowEvent(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="small" type="warning" @click="editRowEvent(row)">编辑</el-button>
            </template>
          </template>
        </vxe-column>
      </vxe-table>
    </card-container>

    <AddSign :is-show.sync="isShowAdd" :users="users" @refresh="getList"></AddSign>
  </div>
</template>

<script>
import { userListNoAuth } from "@/api/common";
import { index } from '@/api/attendance';
import AddSign from "./components/AddSign.vue";
import { deepCopy } from "@/utils";
import { updateSign } from "@/api/attendance";
import { getToken } from "@/utils/auth";

export default {
  components: {
    AddSign
  },
  data() {
    return {
      action: `${process.env.VUE_APP_BASE_API}/api/oa/statistics/import-overtime`,

      isShowAdd: false,
      select: {
        month: this.$moment().format('YYYY-MM'),
        user_id: this.$store.state.user.adminId
      },
      loading: false,
      tableData: [],
      users: []
    }
  },
  methods: {
    getToken,
    uploadData() {
      this.$refs.upload.submit();
    },
    uploadSuccess(response) {
      console.log(response)
      if (response.hasOwnProperty('errcode')) {
        this.$message.error(response.errmsg)
      } else {
        this.$message.success(`已导入${response.total}条`)
        this.getList(true)
      }
    },
    editRowEvent(row) {
      if (!row.attendance.id) {
        this.$message.warning("当前日期无打卡")
        return
      }
      if (this.$refs['table']) {
        this.$refs['table'].setEditRow(row)
      }
    },
    cancelRowEvent(row) {
      if (this.$refs['table']) {
        this.$refs['table'].clearEdit().then(() => {
          // 还原行数据
          this.$refs['table'].revertData(row)
        })
      }
    },
    async saveRowEvent(row) {
      try {
        await this.$confirm('确认保存？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        await this.$refs['table'].clearEdit()
        console.log(row)
        this.loading = true
        await updateSign({
          user_id: this.select.user_id,
          date: row.date,
          sign_in_at: row.attendance.sign_in_at,
          sign_out_at: row.attendance.sign_out_at,
          status: row.attendance.status
        })
        await this.getList()
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },

    async getUsers () {
      try {
        const res = await userListNoAuth({
          page: 1,
          rows: 9999
        })
        this.users = res.data
      } catch (err) {
      }
    },
    async getList () {
      this.loading = true
      try {
        const { attendances	 } = await index(this.select,false)
        this.tableData = attendances
        this.loading = false
      } catch (err) {
        console.error(err)
        this.loading = false
      }
    }
  },
  computed: {
    isActiveStatus() {
      return function(row) {
        if (this.$refs['table']) {
          return this.$refs['table'].isEditByRow(row)
        }
      }
    }
  },
  created() {
    this.getUsers()
    this.getList()
  }
}
</script>

<style scoped lang="scss">
</style>
