<template>
  <div>
    <div class="tabBox" style="overflow: scroll">
      <div class='top-box'>
        <div class='top-box-left'>
          <!-- <span>应签：{{ qdryobj.yq }}</span>
      <span>未签：{{ qdryobj.wq }}</span>
      <span>签到率：{{ qdryobj.qdl }}%</span> -->
        </div>
        <div>
          <el-button v-if="props.state === '0201'" type="primary" @click="supplementarySignIn()"
            v-loading="loadingShow">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>补签</span>
          </el-button>
          <el-button type="primary" @click="dcqdExcel" v-loading="loadingShow">
            <el-icon>
              <Download />
            </el-icon>
            <span>导出签到表</span>
          </el-button>
        </div>
      </div>
      <section style="height: 30vh;">
        <MOSTY.Table :table-columns="TableColumn" :tableData="tableData" :tableloading="tableloading"
          :tableHeight="'100%'" :isSelect="false" style="width: 100%;" :isSort="false">
          <template #depname="{ row }">
            <span class="operate" v-if="row.depname">{{ row.depname }}</span>
            <span class="operate" v-else>{{ row.orgname }}</span>
          </template>
          <template #pxsstype="{ row }">
            <span class="operate" v-if="props.pxsstype == '1'">计划内</span>
            <span class="operate" v-else>计划外</span>
          </template>
          <template #signState="{ row }">
            <span class="operate" v-if="row.signState == 'W'">未签到</span>
            <span class="operate" v-else-if="row.signState == 'D'">已签到</span>
            <span class="operate" v-else>已签离</span>
          </template>
          <template #sfhg="{ row }">
            <span class="operate" v-if="row.signState == 'W'">--</span>
            <span style="color:red" class="operate" v-else-if='row.signState != "W" && row.sfysj && (row.sfhg == "2")'>不合格</span>
            <span class="operate" v-else-if='row.signState != "W" && row.sfysj && row.sfhg == "1"'>合格</span>
            <span class="operate" v-else>--</span>
          </template>
          <template #actions="{ row }">
            <el-popconfirm v-if='row.signState != "W" && row.sfysj && (!row.sfhg || row.sfhg == "2")'
              confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定判为合格?" @confirm="gehg(row, '1')">
              <template #reference>
                <span class="operesee" size="small" style='margin-right:10px;'> 合格</span>
              </template>
            </el-popconfirm>
            <el-popconfirm v-if='row.signState != "W" && row.sfysj && row.sfhg == "1"' confirm-button-text="是"
              cancel-button-text="否" icon-color="red" title="确定判为不合格?" @confirm="gehg(row, '2')">
              <template #reference>
                <span class="operesee" size="small" style='margin-right:10px;'> 不合格</span>
              </template>
            </el-popconfirm>
            <!-- <el-popconfirm v-if="row.signState == 'W' && props.state != '0200'" confirm-button-text="是"
            cancel-button-text="否" icon-color="red" title="确定要签到?"
            @confirm="changesign(row, 'train_in')">
            <template #reference>
                <span class="operate" style="color: yellowgreen">签到</span>
            </template>
        </el-popconfirm>
        <el-popconfirm v-else-if="row.signState == 'D' && props.state != '0200'" confirm-button-text="是"
            cancel-button-text="否" icon-color="red" title="确定要签离?"
            @confirm="changesign(row, 'train_out')">
            <template #reference>
                <span class="operate" style="color: yellowgreen">签离</span>
            </template>
        </el-popconfirm> -->
            <span class="operate" v-if='props.state == "0200"'>-</span>
          </template>
        </MOSTY.Table>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
            @changeSize="handleSizeChange" />

        </div>
      </section>
    </div>
    <!--  补充签到  -->
    <el-dialog v-model="supplementarySignInWin" title="补充签到" width="70%">
      <el-form ref="ruleFormRef" :rules="rules" :model="supplementarySignInFrom" style="width: 100%">
        <el-form-item label="补签时间" prop="date">
          <el-date-picker v-model="supplementarySignInFrom.date" value-format="YYYY-MM-DD" type="date" placeholder="请选择补签时间" />
        </el-form-item>
        <el-form-item label="补签人员:" prop="user_name">
          <el-input v-model="supplementarySignInFrom.user_name" placeholder="选择补签人员" style="width: 400px">
            <template #append>
              <el-button class='cursor' @click="chooseUserVisible = true">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="supplementarySignInWin = false">取消</el-button>
          <el-button type="primary" @click="confirmSupplementarySignature(ruleFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 签到人员选择  -->
    <ChooseUser v-model="chooseUserVisible" :Single="true" :data="memberList" :leaderid="leaderid"
      @choosedUsers="getSonValue" :searchType="'02'"></ChooseUser>

  </div>
</template>
<script setup>
import { ref, onMounted, defineProps, watchEffect, reactive, computed } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { exportXlsx } from "@/excel/Export2Excel.js"
import * as MOSTY from "@/components/MyComponents/index"
import { ElMessage } from "element-plus"
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue"

const props = defineProps({
  id: String,
  pxsstype: String,
  state: String,
  title: String,
  ruleForm: {
    type: Object,
    default: () => {
      return {}
    }
  },
  /** 来自 sjjypxxq 三级教育培训详情 */
  from:String,
})

const qdryobj = ref({
  yq: 0,
  wq: 0,
  qdl: 0
})
const chooseUserVisible = ref(false) // 签到人员选择
const singleShow = ref(false) //单选多选
const tableloading = ref(false)
const tableData = ref([])
const ruleFormRef = ref(null)
const leaderid = ref("")
const memberList = ref([]) //成员选择的id回显
const loadingShow = ref(false)
let supplementarySignInWin = ref(false)
const rules = reactive({
  date: [
    {
      required: true,
      message: "补签时间不能为空",
      trigger: "blur"
    }
  ],
  user_name: [
    {
      required: true,
      message: "补签人员不能为空",
      trigger: "blur"
    }
  ]
})
let supplementarySignInFrom = ref({
  date: "",
  user_name: ""
})
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10
})
const pageData = reactive({
  tableColumns: [
    {
      title: "姓名",
      prop: "name"
    },
    {
      title: "单位",
      prop: "orgname"
    },
    {
      title: "部门",
      prop: "depname",
      slot: true
    },
    {
      title: "已签天数",
      prop: "signInNumber"
    },
    {
      title: "未签天数",
      prop: "notSignInNumber"
    },
    {
      title: "签到时间",
      prop: "signIn"
    },
    {
      title: "合格状态",
      prop: "sfhg",
      slot: true
    },
    // {
    //   title: "签到地点",
    //   prop: "signInAddress"
    // },

    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  pageConfiger: {
    pageSize: 10,
    pageCurrent: 1,
    total: 0
  },
  tableData: []
})
const TableColumn = computed(() => {
  let colArr = pageData.tableColumns
  // 非【三级教育培训实施】移除 “合格状态”
  if(props.from !== 'sjjypxss') colArr = pageData.tableColumns.filter(item => item.title !== "合格状态")
  if (props.ruleForm?.otherType == '09') return colArr
  return colArr.filter(item => item.title !== "操作")
})
watchEffect(() => {
  if (props.id) {
    listQuery.value.id = props.id
    getListData()
    getqdcount()
  }
})
onMounted(() => {

})

//获取考勤表
function getListData() {
  tableloading.value = true
  getApi(listQuery.value, "/mosty-jcgl/training/signPage").then((res) => {
    if (res.records) {
      tableData.value = res.records.map(item => {
        item.signIn = typeof item.signIn === 'string' ? item.signIn : ''
        item.signIn = item.signIn.replace('T', '')
        item.signIn = item.signIn.replace('.000Z', '')
        return item
      })
      tableloading.value = false
      pageData.pageConfiger.total = res.total
    }
  })
}

/**
 * 补签
 */
const confirmSupplementarySignature = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (!valid) return ElMessage.error("必填参数不能为空")
    console.log('supplementarySignInFrom.value: ', supplementarySignInFrom.value);
    postApi({
      ...supplementarySignInFrom.value,
      trainingId: props.id,
      userid: memberList.value
    }, "/mosty-jcgl/training/pcSupplementarySignature").then(() => {
      ElMessage.success("签到成功")
      formEl.resetFields()
      supplementarySignInFrom.value.user_name = ""
      memberList.value = []
      supplementarySignInWin.value = false
      getListData() // 刷新列表
    })
  })
}

/**
 * 选择人员
 * @param value
 */
const getSonValue = (value) => {
  if (supplementarySignInFrom.value.user_name.length) supplementarySignInFrom.value.user_name = ""
  if (memberList.value.length) memberList.value = []
  value.forEach(item => {
    memberList.value.push(item.id)
    supplementarySignInFrom.value.user_name += item.userName + " "
  })
}

/**
 * 补充签到
 */
const supplementarySignIn = () => {
  supplementarySignInWin.value = true
}

//签到情况统计
function getqdcount() {
  getApi({ id: listQuery.value.id }, "/mosty-jcgl/training/signStatistics").then((res) => {
    qdryobj.value.yq = res.countAll
    qdryobj.value.wq = res.countAll - res.qdCount
    if (res.countAll && res.qdCount) {
      qdryobj.value.qdl = Math.floor((res.qdCount / res.countAll) * 100)
    } else {
      qdryobj.value.qdl = 0
    }

  })
}

//签到、签离(签到状态 01-签到 02-签离)
function changesign(val, lab) {
  var data = {
    trainingId: val.trainingId,
    userid: val.userPk

  }
  if (lab == "train_in") {
    data.type = "01"
    postApi(data, "/mosty-jcgl/training/pcSignIn").then(res => {
      ElMessage.success("签到成功")
      getListData()
      getqdcount()

    })
  } else {
    data.type = "02"
    postApi(data, "/mosty-jcgl/training/pcSignIn").then(res => {
      ElMessage.success("签离成功")
      getListData()
      getqdcount()

    })
  }
}

//是否合格
function gehg(val, sfhg) {
  getApi({
    id: val.trainingId,
    sfhg,
    userPk: val.userPk
  }, "/mosty-jcgl/trainingSign/updateSfhg").then(res => {
    ElMessage.success("修改成功")
    getListData()
    getqdcount()
  })

}

//页码发生变化
const handleCurrentChange = (val) => {
  listQuery.value.pageCurrent = val
  pageData.pageConfiger.pageCurrent = val
  getListData()
}
//查询条数发生变化
const handleSizeChange = (val) => {
  listQuery.value.pageSize = val
  pageData.pageConfiger.pageSize = val
  getListData()
}
const getTodayDate = () => {
  const today = new Date()
  let year = today.getFullYear()
  let month = (today.getMonth() + 1).toString().padStart(2, "0")
  let day = today.getDate().toString().padStart(2, "0")
  return `${year}-${month}-${day}`
}
//导出表格
const dcqdExcel = () => {
  loadingShow.value = true
  let title = {
    sort: "序号",
    name: "姓名",
    orgname: "单位",
    depname: "部门",
    signState: "签到状态"
  }
  const param = {
    pageCurrent: 1,
    pageSize: 10000,
    id: listQuery.value.id
  }
  getApi(param, "/mosty-jcgl/training/signPage").then((res) => {
    if (res.records) {
      let data = res.records
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          data[i].sort = (i + 1)
          data[i].types = data[i].pxsstype == "1" ? "计划内" : "计划外"
          if (data[i].signState == "W") {
            data[i].signState = "未签到"
          } else if (data[i].signState == "D") {
            data[i].signState = "已签到"
          } else {
            data[i].signState = "已签离"
          }

        }
        let tablename = "签到情况表.xlsx"
        exportXlsx(title, data, props.title + "签到情况表" + getTodayDate(), tablename)
      } else {
        ElMessage.warning("暂无数据")
      }
    }
  }).finally(() => {
    loadingShow.value = false
  })
}
</script>
<style lang="scss" scoped>
.top-box {
  display: flex;
  justify-content: space-between;
  padding: 10px;

  .top-box-left {
    width: 30%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    >span {
      color: #000;
    }
  }
}

::v-deep .el-form-item__content {
  flex-wrap: nowrap !important;
}

.el-form {
  width: 80vw;
  margin: 0px auto;
  flex-wrap: wrap;
  justify-content: space-between;

}

.el-form-item {
  text-align: center;
}
</style>
