<template>
  <div>
    <card-container>
      <vxe-toolbar>
        <template #buttons>
          <el-button icon="el-icon-plus" type="primary" size="small" @click="isShowAdd = true">新增</el-button>
          <el-button icon="el-icon-search" type="primary" plain size="small" @click="getList">搜索</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="table"
        stripe
        style="margin-top: 10px;"
        :loading="loading"
        keep-source
        show-overflow
        :column-config="{ resizable: true }"
        :edit-rules="validRules"
        :edit-config="{ trigger: 'manual', mode: 'row', showStatus: true, isHover: true, autoClear: false }"
        :align="allAlign"
        :data="tableData"
      >
        <vxe-column type="seq" width="58" align="center" />
        <vxe-column field="date" width="170" title="日期" :edit-render="{}">
          <template #edit="{ row }">
            <el-date-picker v-model="row.date" style="width: 100%;" value-format="yyyy-MM-dd" />
          </template>
        </vxe-column>
        <vxe-column field="user.name" title="值班人员" min-width="160" :edit-render="{}">
          <template #edit="{ row }">
            <el-select
              v-model="row.user_id"
              style="width: 100%;"
            >
              <el-option v-for="user in users" :key="user.id" :value="user.id" :label="user.name" />
            </el-select>
          </template>
        </vxe-column>
        <vxe-column field="leader.name" title="带班领导" min-width="160" :edit-render="{}">
          <template #edit="{ row }">
            <el-select
              v-model="row.leader_id"
              style="width: 100%;"
            >
              <el-option v-for="user in users" :key="user.id" :value="user.id" :label="user.name" />
            </el-select>
          </template>
        </vxe-column>
        <vxe-column field="status" title="值班人员状态" width="120" :edit-render="{}" :formatter="({ cellValue }) => cellValue ? '已完成值班' : '未值班'">
          <template #edit="{ row }">
            <el-select v-model="row.status">
              <el-option :value="0" label="未值班" />
              <el-option :value="1" label="已完成值班" />
            </el-select>
          </template>
        </vxe-column>
        <vxe-column field="leader_status" title="带班领导人员状态" width="120" :edit-render="{}" :formatter="({ cellValue }) => cellValue ? '已完成值班' : '未值班'">
          <template #edit="{ row }">
            <el-select v-model="row.leader_status">
              <el-option :value="0" label="未值班" />
              <el-option :value="1" label="已完成值班" />
            </el-select>
          </template>
        </vxe-column>
        <vxe-column field="remark" min-width="180" title="备注" header-align="center" align="left" :edit-render="{ name: 'input', attrs: { type: 'text' } }" />
        <vxe-column field="operate" title="操作" min-width="220">
          <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>
              <el-button size="small" type="danger" @click="destroyRowEvent(row)">删除</el-button>
            </template>
          </template>
        </vxe-column>
      </vxe-table>

      <el-pagination
        style="margin-top: 10px;"
        :current-page="select.page"
        :page-sizes="[20, 30, 40, 50]"
        :page-size="select.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="e => {
          select.page_size = e;
          select.page = 1;
          getList();
        }"
        @current-change="e => {
          select.page = e;
          getList();
        }"
      />
    </card-container>
    <add-be-on-duty ref="AddBeOnDuty" :users="users" :is-show.sync="isShowAdd" @refresh="getList" />
  </div>
</template>

<script>
import { deepCopy } from '@/utils'
import { index, save, destroy } from '@/api/onDutySchedules'
import { index as userIndex } from '@/api/user'
import AddBeOnDuty from './components/AddBeOnDuty.vue'
export default {
  components: {
    AddBeOnDuty
  },
  data() {
    return {
      users: [],
      isShowAdd: false,

      loading: false,
      select: {
        page: 1,
        page_size: 20,
        show_relation: ['user', 'leader']
      },
      total: 0,
      allAlign: null,
      tableData: [],
      validRules: {
        date: [
          { required: true, message: '请选择日期' }
        ],
        user_id: [
          { required: true, message: '请选择值班人员' }
        ],
        leader_id: [
          { required: true, message: '请选择带班领导' }
        ]
      },
      form: {
        id: '',
        date: '',
        user_id: '',
        leader_id: '',
        leader_status: '',
        status: '',
        remark: ''
      }
    }
  },
  computed: {
    isActiveStatus() {
      return function(row) {
        if (this.$refs['table']) {
          return this.$refs['table'].isEditByRow(row)
        }
      }
    }
  },
  created() {
    this.getUsers()
    this.getList()
  },
  methods: {
    editRowEvent(row) {
      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 getUsers() {
      try {
        const res = await userIndex({
          rows: 999
        })
        this.users = res.data
      } catch (err) {
        console.error(err)
      }
    },

    async getList() {
      this.loading = true
      try {
        const res = await index(this.select)
        this.tableData = res.data
        this.total = res.total
        this.loading = false
      } catch (err) {
        console.error(err)
        this.loading = false
      }
    },

    async saveRowEvent(row) {
      try {
        const errMap = await this.$refs['table'].validate()
        if (errMap) {
          throw new Error(errMap)
        }
        await this.$confirm('确认保存？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        await this.$refs['table'].clearEdit()
        const form = deepCopy(this.form)
        for (const key in form) {
          form[key] = row[key]
        }
        if (!form.password) {
          delete form.password
        }
        this.loading = true
        await save(form)
        await this.getList()
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },
    async destroyRowEvent(row) {
      try {
        await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        this.loading = true
        if (row.id) {
          await destroy({
            id: row.id
          })
          await this.getList()
        } else {
          console.log(row)
          this.tableData.splice(this.tableData.findIndex(i => i._X_ROW_KEY === row._X_ROW_KEY), 1)
        }
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.total {
  color: #666;
  text-align: right;
  line-height: 3;
}
::v-deep .el-tag + .el-tag {
  margin-left: 4px;
}
</style>
