<template>
  <div class="app-container" v-loading="loading">
    <el-row :gutter="20">
      <el-col :span="16">

        <el-header>
          <div style="">
            <span>签到表</span>
            <span style="float:right;">
              <el-date-picker
                v-model="queryParams.selectTime"
                value-format="yyyy-MM-dd"
                type="month"
                @change="getList()"
                placeholder="选择月">
              </el-date-picker>
            </span>
          </div>
        </el-header>
        <table>
          <thead>
          <tr>
            <th width="80"></th>
            <th v-for="(item,index) in dateLength" :class="selectHead===index+1?'selectBox':''"
                @click="selectMany(index+1)">
              {{ index + 1 }}
            </th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(item,index) in userList">
            <td :class="(item.userId===selectUser.userId || selectAll)?'selectBox':''">{{ item.nickName }}</td>
            <td style="font-size: small" v-for="(item2,index2) in dateLength"
                @click="selectAttendDay(item,index,index2+1)"
                :style="{backgroundColor:(item.attendances.length>0 && item.attendances.findIndex(i=>i.attendanceDay === index2+1) >-1) ?
                (item.attendances[item.attendances.findIndex(i=>i.attendanceDay === index2+1)].projectId!==0?item.attendances[item.attendances.findIndex(i=>i.attendanceDay === index2+1)].color:'#fdf6e4'):
                (index2+1===selectIndex&&(item.userId===selectUser.userId || selectAll)?'#f3ff52':'')}"
            >
              {{ item.attendances.length > 0 && item.attendances.findIndex(i => i.attendanceDay === index2 + 1) > -1 && item.attendances[item.attendances.findIndex(i => i.attendanceDay === index2 + 1)].projectId === 0 ? '出差' : '' }}
            </td>
          </tr>
          </tbody>
        </table>
      </el-col>
      <el-col :span="8">

        <div>

          <el-header> 操作栏</el-header>
          <el-card class="box-card">
            <el-button @click="removeAttendance" type="danger" plain>取消操作</el-button>
            <el-button @click="toTravel" type="warning" plain>出差</el-button>
          </el-card>
          <el-card class="box-card">
            <div slot="" class="">
              <span><i class="el-icon-s-order"></i> 项目列表</span>
              <!--            <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>-->
            </div>
            <div style="height: 250px;overflow: auto">
              <div v-for="(item,index) in sortedProjects" style="display: flex;justify-content: space-between;">
                <el-button class="text" :style="{backgroundColor:item.color===''?'':item.color}" @click="signIn(item)">
                  {{ item.projectName }}
                </el-button>
                <el-color-picker class="color-picker" v-model="item.color"
                                 @change="changeItemColor(item)"></el-color-picker>
              </div>
            </div>
          </el-card>
          <el-card class="box-card">
            <div slot="" class="">
              <span><i class="el-icon-timer"></i>工作时长</span>
              <div style="margin: 20px 0 ">
                <el-radio-group v-model="timeFlag">
                  <el-radio :label="0">天计</el-radio>
                  <el-radio :label="1">小时计</el-radio>
                </el-radio-group>
              </div>
              <el-select v-if="timeFlag===0" v-model="form.dayLength" placeholder="请选择工作时长">
                <el-option
                  v-for="dict in dict.type.work_time_length"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>

              <el-select v-if="timeFlag===1" v-model="form.hour" placeholder="请选择工作时长">
                <el-option
                  v-for="dict in dict.type.work_time_length_hour"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </div>
          </el-card>
        </div>


      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb8">
      <el-col :span="2">
        <span class="demonstration">计算月份:</span>
      </el-col>
      <el-col :span="6">
        <div class="block">
          <el-date-picker
            v-model="date"
            type="month"
            placeholder="选择日期">
          </el-date-picker>
        </div>
      </el-col>
      <el-col :span="1.5">

        <el-button @click="calcWork">计算</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-table
          :data="userList"
          stripe
          style="width: 100%">

          <el-table-column
            type="index"
            label="序号"
            width="180">
          </el-table-column>
          <el-table-column
            prop="nickName"
            label="员工姓名"
            width="180">
          </el-table-column>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="calcFlag"
                @click="handleCalc(scope.row)"
                v-hasPermi="['oa:oaWarehouse:edit']"
              >查看考勤结果
              </el-button>
              <el-button
                size="mini"
                type="text"
                v-else
                disabled
                icon="el-icon-edit"
                @click="handleCalc(scope.row)"
                v-hasPermi="['oa:oaWarehouse:edit']"
              >请选择日期计算
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="12">
        <bar-chart :projectList="projects"></bar-chart>
      </el-col>

    </el-row>


    <el-dialog
      title="计算结果"
      :visible.sync="showCalc"
      width="70%"
    >

      <div class="container">
        <h1>员工个人财务与签到报告 - {{ calcUser.nickName }}</h1>

        <!-- 员工基本信息 -->
        <div class="employee-info">
          <p><strong>员工姓名：</strong> {{ calcUser.nickName }}</p>
          <p><strong>职位：</strong> 员工</p>
        </div>

        <!-- 月度工作情况表格 -->
        <h2>{{ date.getMonth() }} 月度工作签到情况</h2>


        <el-descriptions class="margin-top" title="报告详情" :column="3" :size="size" border>
          <template slot="extra">
            <div>总工作时长（天）：{{ calcResultItem.workTimes }}</div>
          </template>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              员工姓名
            </template>
            {{ calcUser.nickName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-mobile-phone"></i>
              人力成本
            </template>
            {{ calcUser.laborCost }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">

              当月估计(￥)
            </template>
            {{ calcUser.laborCost * calcResultItem.workTimes }}
          </el-descriptions-item>
        </el-descriptions>


        <el-table
          :data="calcResultAttendances"
          stripe
          style="width: 100%">
          <el-table-column
            prop="projectName"
            label="项目名"
            width="180">
            <template slot-scope="scope">
              <div>{{ scope.row.projectId === 0 ? '出差' : scope.row.projectName }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="count"
            label="签到（天）"
            width="180">
          </el-table-column>
          <el-table-column
            prop="workTimes"
            label="工作时长（天）">
          </el-table-column>
          <el-table-column
            prop="hourWorkTimes"
            label="工作时长（小时计）">
          </el-table-column>
        </el-table>


        <div class="footer">
          <p style="color: red">注：小时计与天计为单独记录计算</p>
          <p>© 2024 财务与签到报告 | 由公司财务部门生成</p>
        </div>
      </div>


      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="showCalc = false">关闭</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>

import {listWorker} from "@/api/system/user";
import {listProject, updateProject} from "@/api/oa/project";
import {listOaAttendance} from "@/api/oa/oaAttendance";
import {
  addBatchOaAttendance,
  addOaAttendance,
  delOaAttendance,
  getDateLength,
  workCalc,
  delOaAttendanceAll
} from "../../../api/oa/oaAttendance";
import item from "../../../layout/components/Sidebar/Item.vue";
import BarChart from "../../dashboard/BarChart.vue";
import {projectData} from "../../../api/oa/project";

export default {
  name: "Project",
  components: {BarChart},
  dicts: ['work_time_length', 'work_time_length_hour'],
  data() {
    return {
      // 选择索引
      selectIndex: new Date().getDate(),
      // 用户列表
      userList: [],
      // 计算结果
      calcFlag: false,
      // 项目列表
      projectList: [],
      loading: true,
      selectHead: new Date().getDate(),
      // 当前月的天数
      dateLength: 31,
      // 计算提交月份
      date: new Date(),
      // 提交表单
      form: {},
      showCalc: false,
      // 查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      calcUser: {},
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        selectTime: new Date(),
      },
      selectArrayIndex: new Date().getDate(),
      timeFlag: 0,
      // 项目查询参数
      projectQueryParams: {
        pageNum: 1,
        pageSize: 99,
        projectStatus: 0,
        projectName: undefined,
        projectNum: undefined,
        beginTime: undefined,
        finishTime: undefined
      },
      selectUser: {},
      // 日期范围
      dateRange: [],
      selectAll: true,
      calcResult: [],
      calcResultItem: {},
      calcResultUser: {},
      calcResultAttendances: [],
      calcResultProject: {},
      projects:[]

    }
  },
  mounted() {

  },
  created() {

    this.getDate();
    this.getProjectData();
    this.getList();
  },
  computed: {
    sortedProjects() {
      let projectList = [...this.projectList];
      projectList.sort((a, b) => {
        if (a.color && !b.color) return -1;
        if (!a.color && b.color) return 1;
        return 0;
      });
      return projectList;
    }
  },

  methods: {

    // 获取条形图数据
    getProjectData(){
      projectData().then(res => {
        this.projects = res.data;
      })
    },
    // 出差标记
    toTravel() {
      if (!this.selectAll) {
        this.form = {
          projectId: 0,
          userId: this.selectUser.userId,
          attendanceDay: this.selectIndex,
        }
        addOaAttendance(this.form).then(res => {
          this.getList()
          this.selectUser = this.selectArrayIndex >= this.userList.length - 1 ? this.selectUser : this.userList[this.selectArrayIndex + 1]

        })
      } else {
        this.form = {
          projectId: 0,
          attendanceDay: this.selectIndex,
        }
        // 集体赋予状态
        addBatchOaAttendance(this.form).then(res => {
          this.getList()
        })
      }
    },

    // 删除签到
    removeAttendance() {
      if (!this.selectAll) {
        const attendanceId = this.selectUser.attendances.find(item => item.attendanceDay === this.selectIndex).id
        delOaAttendance(attendanceId).then(res => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        })
      } else {
        delOaAttendanceAll(this.selectIndex).then(res => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        })
      }

    },

    // 查看计算结果
    handleCalc(row) {
      this.showCalc = true;
      this.calcUser = row
      this.calcResultItem = this.calcResult.filter(item => item.sysUser.userId === this.calcUser.userId)[0]
      this.calcResultAttendances = this.calcResultItem.attendances
    },

    // 计算
    calcWork() {
      workCalc(this.date).then(res => {
        this.calcResult = res.data;
        this.calcFlag = true;
      })
    },

    getDate() {
      getDateLength().then(res => {
        this.dateLength = res.data;
      })
    },

    selectAttendDay(item, index, index2) {
      this.selectIndex = index2;
      this.selectAll = false;
      this.selectUser = item;
      this.selectHead = index2
      this.selectArrayIndex = index
    },

    selectMany(index) {
      this.selectAll = true;
      this.selectIndex = index;
      this.selectHead = index
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listOaAttendance(this.queryParams).then(res => {
        this.userList = res.rows;
        console.log(this.userList);
        this.dateLength = res.total;
        this.loading = false;
      });
      listProject(this.projectQueryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
      })
    },

    changeItemColor(item) {
      updateProject(item).then(res => {
        this.getList();
      })

    },
    signIn(project) {
      // 一个签到
      if (this.form.dayLength === undefined && this.timeFlag === 0) {
        this.$message({message: '请选择工作时长', type: 'warning'})
        return;
      }
      if (this.form.hour === undefined && this.timeFlag === 1) {
        this.$message({message: '请选择工作时长', type: 'warning'})
        return;
      }
      let time = this.timeFlag === 0 ? this.form.dayLength : this.form.hour


      if (!this.selectAll) {
        this.form = {
          projectId: project.projectId,
          userId: this.selectUser.userId,
          attendanceDay: this.selectIndex,
          dayLength: this.timeFlag === 0 ? this.form.dayLength : undefined,
          hour: this.timeFlag === 1 ? this.form.hour : undefined
        }
        addOaAttendance(this.form).then(res => {
          this.selectUser = this.selectArrayIndex >= this.userList.length - 1 ? this.selectUser : this.userList[this.selectArrayIndex + 1]
          this.getList()
        })
      } else {

        this.form = {
          projectId: project.projectId,
          attendanceDay: this.selectIndex,
          dayLength: this.timeFlag === 0 ? this.form.dayLength : undefined,
          hour: this.timeFlag === 1 ? this.form.hour : undefined
        }
        // 集体赋予状态
        addBatchOaAttendance(this.form).then(res => {
          this.getList()
        })
      }

    },

  }
};
</script>
<style scoped>
table {
  border: 1px solid #000;
  table-layout: fixed;
  width: 100%;
}

th {
  border: 1px solid;

  height: 15px;
  overflow: hidden;
}

td {
  border: 1px solid;
  white-space: nowrap;
}

table {
  border-collapse: collapse;
}

.selectDay {
  background-color: #00afff;
}

.selectBox {
  background-color: #f3ff52;
}

.text {
  font-size: 16px;
  width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  border-bottom: #cccccc 1px dashed;
  margin: 5px 0;
}

.color-picker {
  font-size: 16px;
  width: 30%;


  border-bottom: #cccccc 1px dashed;
  margin: 5px 0;
}

.el-header, .el-footer {
  background-color: #f6f6f6;
  color: #333;
  text-align: center;
  line-height: 60px;
  border-radius: 7px 7px 0 0;
}
</style>
