<template>
  <div class="app-container">
    <el-form ref="queryForm" class="lookForm" :model="queryParams" size="mini" :inline="true" label-width="140px">
      <el-form-item label="岗位名称" prop="postName">
        <el-input v-model="queryParams.postName" placeholder="请输入岗位名称" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设岗部门" prop="deptName">
        <el-input v-model="queryParams.deptName" placeholder="请输入设岗部门" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="applyStatus">
        <el-select v-model="queryParams.applyStatus" placeholder="请选择审核状态" clearable>
          <el-option v-for="dict in dict.type.qgzx_stu_post_status" :key="dict.value" :label="dict.label"
                     :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工作日期" prop="workDate">
        <el-date-picker v-model="queryParams.workDate" clearable type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择工作日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button icon="el-icon-plus" plain type="success" size="mini" @click="addVClick">填报</el-button>
    <span style="color: red;">
      <!-- *每周不超过8小时, -->
      固定岗位B每月不超过40小时,固定岗位A每月不超过当月的工作日.
    </span>
    <span>本月已填报{{ monthTime }} (不含拒绝)</span>


    <el-table v-loading="loading" :data="tableData">
      <el-table-column label="#" align="center" prop="id" />
      <el-table-column label="学号" align="center" prop="stuNo" />

      <el-table-column label="姓名" align="center" prop="stuName" />
      <el-table-column label="学院" align="center" prop="stuDept" />

      <el-table-column label="岗位名称" align="center" prop="postName" />
      <el-table-column label="岗位类型" align="center" prop="postType" />
      <el-table-column label="设岗部门" align="center" prop="deptName" />
      <el-table-column label="工作日期" align="center" prop="workDate" />

      <el-table-column label="工作时长" align="center">
        <template #default="{ row }">
          {{ row.postType == "固定岗位A" ? row.workTime + "天" : row.workTime + "小时" }}
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applyTime" width="170px" />

      <el-table-column label="审核状态" align="center" prop="applyStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qgzx_stu_post_status" :value="scope.row.applyStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.applyStatus == '0'" size="mini" type="text" icon="el-icon-edit"
                     @click="editVClick(scope.row)"
          >修改</el-button>
          <el-button v-if="scope.row.applyStatus == '0' || scope.row.applyStatus == '1'" size="mini"
                     type="text" icon="el-icon-close" @click="cancelApply(scope.row)"
          >取消申请</el-button>
          <el-button v-if="scope.row.applyStatus != '0'" size="mini" type="text" icon="el-icon-view"
                     @click="lookVClick(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>



    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"
    />



    <el-dialog title="填报" :visible.sync="editV">
      <el-form ref="applyForm" class="lookForm" size="mini" label-width="148px">
        <el-form-item label="工作岗位">
          <StuOwnPostSelect v-model="applyForm.stuPostId" />
        </el-form-item>
        <el-form-item label="工作日期">
          <el-date-picker v-model="applyForm.workDate" :picker-options="pickerOptions" align="right"
                          type="date" placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item :label="postType == '固定岗位A' ? '工作时长(单位:天)' : '工作时长(单位:小时)'">
          <el-input v-model="applyForm.workTime" type="number" />
        </el-form-item>
        <el-form-item label="主要工作">
          <el-input v-model="applyForm.mainWork" :maxlength="200" type="textarea" />
        </el-form-item>
        <el-form-item label="工作附件">
          <ImageUpload v-model="applyForm.workMaterial" />
        </el-form-item>
        <el-form-item label="">
          <!-- <el-button plain type="primary" @click="doSave">保存</el-button> -->
          <el-button plain type="success" @click="doApply">提交</el-button>
          <span style="color: red;">
            <!-- *每周不超过8小时, -->
            每月不超过40小时.
          </span>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="查看" :visible.sync="lookV">
      <el-form ref="applyForm" class="lookForm" size="mini" label-width="148px">
        <el-form-item label="工作岗位">
          <el-input v-model="lookForm.postName" readonly />
        </el-form-item>
        <el-form-item label="工作日期">
          <el-input v-model="lookForm.workDate" readonly />
        </el-form-item>
        <el-form-item label="工作时长(单位:小时 /天)">
          <el-input v-model="lookForm.workTime" readonly />
        </el-form-item>
        <el-form-item label="主要工作">
          <el-input v-model="lookForm.mainWork" type="textarea" readonly />
        </el-form-item>
        <el-form-item label="工作附件">
          <ImagePreview width="200px" height="200px" :src="lookForm.workMaterial" />
        </el-form-item>

        <el-form-item v-if="!isEmpty(lookForm.zdlsCmt)" label="审核意见">
          <el-radio-group v-model="lookForm.zdlsCmt" disabled>
            <el-radio :label="'通过'">通过</el-radio>
            <el-radio :label="'不通过'">不通过</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!isEmpty(lookForm.zdlsCmt)" label="指导老师签章">
          <img v-if="lookForm.zdlsSign" :src="baseurl + lookForm.zdlsSign" width="200px" height="50px"
               class="avatar"
          >
        </el-form-item>
        <el-form-item v-if="!isEmpty(lookForm.zdlsCmt)" label="审核时间">
          <el-input v-model="lookForm.zdlsTime" readonly />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>

import StuOwnPostSelect from '@/views/workstudy/components/StuOwnPostSelect'

import { fullLoading, isEmpty } from '@/api/helpFunc'
import { cancelApply, computeTimeByStuNo, doApply, doSave, listOwnApply as getList } from '@/api/workstudy/worklog'

import { listOwnCanSelectPost } from '@/api/workstudy/stuPost'
import dayjs from 'dayjs'


export default {
    name: 'WorkstudyWorkLogStu',
    dicts: ['qgzx_stu_post_status'],
    components: {
        StuOwnPostSelect
    },
    data() {
        return {
            editV: false,
            baseurl: process.env.VUE_APP_BASE_API + '/',
            isEmpty,
            loading: false,

            tableData: [],
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                postName: null
            },

            applyForm: {

            },
            pickerOptions: {
                disabledDate(time) {
                    //return false  // 完全开放日期选择,五天后,关闭
                    const today = new Date()
                    const currentDate = new Date(today.getFullYear(), today.getMonth(), today.getDate())
                    const fiveDaysAgo = new Date(today.getFullYear(), today.getMonth(), 5)

                    // 获取当前月份的第一天和最后一天  
                    const firstDayOfCurrentMonth = new Date(today.getFullYear(), today.getMonth(), 1)
                    const lastDayOfCurrentMonth = new Date(
                        today.getFullYear(),
                        today.getMonth() + 1,
                        0
                    )

                    // 获取上个月的第一天和最后一天  
                    const firstDayOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1)
                    const lastDayOfLastMonth = new Date(
                        today.getFullYear(),
                        today.getMonth(),
                        0
                    )

                    // 判断今天是否在当前月份的前五天  
                    const isWithinLastFiveDays = currentDate <= fiveDaysAgo

                    // 如果今天在当前月份的前五天内,允许选择上个月的日期  
                    if (isWithinLastFiveDays) {
                        return time < firstDayOfLastMonth || time > lastDayOfCurrentMonth
                    } else {
                        // 否则,只允许选择当前月份及以后的日期  
                        return time < firstDayOfCurrentMonth || time > lastDayOfCurrentMonth
                    }
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date())
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date()
                        date.setTime(date.getTime() - 3600 * 1000 * 24)
                        picker.$emit('pick', date)
                    }
                }]
            },

            lookV: false,
            lookForm: {},

            monthTime: 0,

            postType: '',
        }
    },
    created() {
        this.computeTimeByStuNo()
        this.getList()
    },
    methods: {

        async listOwnCanSelectPost() {
            let loading = fullLoading(this)
            let res = await listOwnCanSelectPost()
            loading.close()
            if (res.code == 200) {
                let data = [...res.rows]
                if (!isEmpty(data)) {
                    let stuPost = data[0]
                    console.log(stuPost.id)
                    this.postType = stuPost.postType
                    this.applyForm.stuPostId = stuPost.id
                }
            }
        },
        async computeTimeByStuNo() {
            let res = await computeTimeByStuNo()
            if (res.code == 200) {
                let data = { ...res.data }
                if (!isEmpty(data.workTime)) {
                    this.monthTime = data.workTime
                }
            }
        },
        lookVClick(row) {
            this.lookForm = {}
            this.lookForm = { ...row }
            this.lookV = true
        },
        cancelApply(row) {
            let id = row.id
            this.$confirm('您确定要取消申请吗, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let loading = fullLoading(this)
                let res = await cancelApply(id)
                loading.close()
                if (res.code == 200) {
                    this.$message.success(res.msg)
                    this.getList()
                }
            }).catch(() => {

            })
        },
        editVClick(row) {
            this.applyForm = {}
            this.applyForm = { ...row }
            this.editV = true
        },
        async addVClick() {
            await this.listOwnCanSelectPost()
            this.applyForm = {}
            this.editV = true
        },
        async doSave() {
            let sdata = { ...this.applyForm }

            if (isEmpty(sdata.stuPostId)) {
                this.$message.info('请选择岗位')
                return
            }

            if (isEmpty(sdata.workDate)) {
                this.$message.info('请选择工作日期')
                return
            }

            if (isEmpty(sdata.workTime)) {
                this.$message.info('请输入工作时长')
                return
            }

            if (this.postType != '固定岗位A' ) {
                if (sdata.workTime <= 0 || sdata.workTime > 8) {
                    this.$message.info('请输入正确的工作时长(每天工作时长不能超过8小时)')
                    return
                }
            }

            if (sdata.workTime.toString().indexOf('.') > -1) {
                if (! /(\.5)$/.test(sdata.workTime.toString())) {
                    this.$message.info('请输入正确的工作时长(小数点后只能以.5结尾)')
                    return
                }
            }


            if (isEmpty(sdata.mainWork)) {
                this.$message.info('请输入主要工作')
                return
            }
            if (isEmpty(sdata.workMaterial)) {
                this.$message.info('请上传工作附件')
                return
            }

            sdata.workDate = dayjs(sdata.workDate).format()
            let loading = fullLoading(this)
            let res = await doSave(sdata)
            loading.close()
            if (res.code == 200) {
                this.$message.success(res.msg)
                this.getList()
                this.computeTimeByStuNo()
                this.editV = false
            }

        },
        async doApply() {
            let sdata = { ...this.applyForm }
            console.log(sdata)
            if (isEmpty(sdata.stuPostId)) {
                this.$message.info('请选择岗位')
                return
            }

            if (isEmpty(sdata.workDate)) {
                this.$message.info('请选择工作日期')
                return
            }

            if (isEmpty(sdata.workTime)) {
                this.$message.info('请输入工作时长')
                return
            }

            if (sdata.workTime.toString().indexOf('.') > -1) {
                if (! /(\.5)$/.test(sdata.workTime.toString())) {
                    this.$message.info('请输入正确的工作时长(小数点后只能以.5结尾)')
                    return
                }
            }

            if (isEmpty(sdata.mainWork)) {
                this.$message.info('请输入主要工作')
                return
            }
            if (isEmpty(sdata.workMaterial)) {
                this.$message.info('请上传工作附件')
                return
            }
            sdata.workDate = dayjs(sdata.workDate).format()

            let loading = fullLoading(this)
            let res = await doApply(sdata)
            loading.close()
            if (res.code == 200) {
                this.$message.success(res.msg)
                this.getList()
                this.computeTimeByStuNo()
                this.editV = false
            }
        },

        async getList() {
            this.loading = true
            let res = await getList(this.queryParams)
            this.loading = false
            if (res.code == 200) {
                this.tableData = [...res.rows]
                this.total = res.total
            }
        },
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
    }
}

</script>


<style scoped lang="scss">
.lookForm {
    .el-form-item {
        margin-bottom: 5px;
    }
}
</style>