<template>
  <div class="app-container" id="leaveReporting">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="休假时间" prop="leaveDate">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>

      </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['flow:leaveReporting:add']"
        >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList">
      <el-table-column label="序号" align="center" width="80" type="index">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="userName" width="100"/>
      <el-table-column label="职务" align="center" prop="postName" :show-overflow-tooltip="true" width="240"/>
      <el-table-column label="所属部门" align="center" prop="orgName" :show-overflow-tooltip="true" width="240">
      </el-table-column>
      <el-table-column label="休假类型" align="center" prop="leaveType" width="100"/>

      <el-table-column label="休假开始时间" align="center" prop="leaveStartDate" :show-overflow-tooltip="true" width="180">
        <template slot-scope="scope">
          <div>{{ scope.row.leaveStartDate }}
<!--            <span v-show="scope.row.leaveStartInterval=='1'">上午</span>-->
<!--            <span v-show="scope.row.leaveStartInterval=='2'">下午</span>-->
          </div>
        </template>
      </el-table-column>

      <el-table-column label="休假结束时间" align="center" prop="leaveEndDate" :show-overflow-tooltip="true" width="180">
        <template slot-scope="scope">
          <div>{{ scope.row.leaveEndDate }}
<!--            <span v-show="scope.row.leaveEndInterval=='1'">上午</span>-->
<!--            <span v-show="scope.row.leaveEndInterval=='2'">下午</span>-->
          </div>
        </template>
      </el-table-column>

      <el-table-column label="休假时长(天)" align="center" prop="leaveDuration" :show-overflow-tooltip="true"
                       width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding">
        <template slot-scope="scope">
          <el-button
            size="mini" type="primary"
            v-hasPermi="['flow:leaveReporting:edit']"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-button
            size="mini" type="danger"
            v-hasPermi="['flow:leaveReporting:remove']"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>

          <el-button
            size="mini" type="primary"
            v-hasPermi="['flow:leaveReporting:list']"
            @click="handleDetails(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="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名：" prop="userName">
              <el-input v-model="form.userName" :readonly="true"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="职位：" prop="postName">
              <el-input v-model="form.postName" :readonly="true"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="所属部门:" prop="orgId">
              <el-select v-model="form.orgId" @change="changDept" style="width: 100%;">
                <el-option
                  v-for="item in orgList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="休假类型:" prop="leaveType">
              <el-select v-model="form.leaveType" @change="changType" filterable style="width: 100%;">
                <el-option
                  v-for="item in typeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="休假开始时间：" prop="leaveStartDate">
              <el-date-picker
                v-model="form.leaveStartDate" :clearable="false"
                type="date" value-format="yyyy-MM-dd" style="width: 100%;" @change="handleDateChange"
                placeholder="休假开始时间" :pickerOptions="startPickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
<!--          <el-col :span="4">
            <el-form-item prop="leaveStartInterval" label-width="0px">
              <el-select v-model="form.leaveStartInterval" style="width: 80%;margin-left: 30px;"
                         @change="handleDateChange">
                <el-option
                  v-for="item in timeStatusList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="休假结束时间:" prop="leaveEndDate">
              <el-date-picker
                v-model="form.leaveEndDate" :clearable="false"
                type="date" value-format="yyyy-MM-dd" style="width: 100%;" @change="handleDateChange"
                placeholder="休假结束时间" :pickerOptions="endPickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
<!--          <el-col :span="4">
            <el-form-item prop="leaveEndInterval" label-width="0px">
              <el-select v-model="form.leaveEndInterval" style="width: 80%;margin-left: 30px;"
                         @change="handleDateChange">
                <el-option
                  v-for="item in timeStatusList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="休假时长(天)：" prop="leaveDuration">
              <el-input v-model="form.leaveDuration" :readonly="true"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="地点：" prop="location">
              <el-input v-model="form.location" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="是否请示领导同意：" prop="isAgree">
              <el-radio-group v-model="form.isAgree">
                <el-radio
                  v-for="item in isAgreeList"
                  :key="item.id"
                  :label="item.id"
                >{{item.name}}</el-radio>
              </el-radio-group>


            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="代理主持工作人员：" prop="hostUserId">
              <el-select v-model="form.hostUserId" multiple  placeholder="请选择人员姓名" filterable clearable style="width: 100%;">
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                />
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="休假事由：" prop="leaveReason">
              <el-input type="textarea" v-model="form.leaveReason" maxlength="200"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row >
          <el-col :span="24">
            <el-form-item label="备注：" prop="remark">
              <el-input type="textarea" v-model="form.remark" maxlength="200"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="openView" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名：" prop="userName">
              <el-input v-model="form.userName" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="职位：" prop="postName">
              <el-input v-model="form.postName" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="所属部门:" prop="orgId">
              <el-input v-model="form.orgName" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="休假类型:" prop="leaveType">
              <el-select v-model="form.leaveType" @change="changType" filterable style="width: 100%;" :disabled="true">
                <el-option
                  v-for="item in typeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="休假开始时间：" prop="leaveStartDate">
              <el-date-picker
                v-model="form.leaveStartDate" :clearable="false"
                type="date" value-format="yyyy-MM-dd" style="width: 100%;" @change="handleDateChange"
                placeholder="休假开始时间" :pickerOptions="startPickerOptions" :disabled="true">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="休假结束时间:" prop="leaveEndDate">
              <el-date-picker
                v-model="form.leaveEndDate" :clearable="false"
                type="date" value-format="yyyy-MM-dd" style="width: 100%;" @change="handleDateChange"
                placeholder="休假结束时间" :pickerOptions="endPickerOptions" :disabled="true">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="休假时长(天)：" prop="leaveDuration">
              <el-input v-model="form.leaveDuration" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="地点：" prop="location">
              <el-input v-model="form.location" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="是否请示领导同意：" prop="isAgree">
              <el-radio-group v-model="form.isAgree" :disabled="true">
                <el-radio
                  v-for="item in isAgreeList"
                  :key="item.id"
                  :label="item.id"
                >{{item.name}}</el-radio>
              </el-radio-group>


            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="代理主持工作人员：" prop="hostUserId">
              <el-input v-model="form.hostUserName" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="休假事由：" prop="leaveReason">
              <el-input type="textarea" :disabled="true" v-model="form.leaveReason" maxlength="200"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row >
          <el-col :span="24">
            <el-form-item label="备注：" prop="remark">
              <el-input type="textarea" :disabled="true" v-model="form.remark" maxlength="200"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLeaveReporting,
  getLeaveReporting,
  delLeaveReporting,
  addLeaveReporting,
  updateLeaveReporting,
  getPostName,
  getUserList,
  exportLeaveReporting,
  getDaysDate,
  leaveReporting
} from "@/api/process/leaveReporting";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getSelectRole} from "@/api/system/userInfo";
import {listDeptUser} from "@/api/system/dept";
// 转换函数
function transformToTypeList(data) {
  return data.map(item => ({
    id: item.dictLabel,
    name: item.dictLabel
  }));
}
export default {
  name: "LeaveReporting",
  dicts: ['att_status'],
  components: {Treeselect},
  data() {
    return {
      userInfo: this.$store.state.user,
      orgList: this.$store.state.user.orgList,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      userList:[],
      isAgreeList:[{id:'0',name:'否'},{id:'1',name:'是'}],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openView: false,
      isEdit: false,
      timeStatusList: [{id: '1', name: "上午"}, {id: '2', name: "下午"}],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      personOptions: [],

      typeList: [],

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orgId: [
          {required: true, message: "所属部门不能为空", trigger: "blur"}
        ],
        leaveType: [
          {required: true, message: "休假类型不能为空", trigger: "blur"}
        ],
        leaveStartDate: [
          {required: true, message: "休假开始时间不能为空", trigger: "blur"}
        ],
        // leaveStartInterval: [
        //   {required: true, message: "不能为空", trigger: "change"}
        // ],
        leaveEndDate: [
          {required: true, message: "休假结束时间不能为空", trigger: "blur"}
        ],
        // leaveEndInterval: [
        //   {required: true, message: "不能为空", trigger: "change"}
        // ],
        leaveDuration: [
          {required: true, message: "休假时长不能为空", trigger: "blur"}
        ],

        isAgree: [
          {required: true, message: "是否请示领导同意不能为空", trigger: "blur"}
        ],
        hostUserId: [
          {required: true, message: "代理主持工作人员不能为空", trigger: "blur"}
        ],
        leaveReason: [
          {required: true, message: "休假事由不能为空", trigger: "blur"}
        ],
      },
      // 开始日期选择限制
      startPickerOptions: {
        disabledDate: (v) => {
          const today = new Date()
          today.setHours(0, 0, 0, 0)
          if (this.form.leaveEndDate) {
            const end = new Date(this.form.leaveEndDate);
            end.setHours(0, 0, 0, 0);
            return v.getTime() > end.getTime() || v.getTime() < today.getTime();
          }
          return v.getTime() < today.getTime()
        },
      },
      // 结束日期选择限制
      endPickerOptions: {
        disabledDate: (v) => {
          const today = new Date()
          today.setHours(0, 0, 0, 0)
          if (this.form.leaveStartDate) {
            return v.getTime() < new Date(this.form.leaveStartDate).getTime() - 86400000; //  - 86400000是否包括当天
          }
          return v.getTime() < today.getTime()
        },
      },
      daysNumber:"",
    };
  },
  created() {
    this.getList();
    this.getUserLists();
    this.getLeaveReporting();
  },
  methods: {
    getLeaveReporting(){
      leaveReporting().then(response => {
        // 使用转换函数生成 typeList
        const list = transformToTypeList(response.data);
        this.typeList = list;
      });
    },

    async handleDateChange() {
      this.form.leaveStartInterval = 1;
      this.form.leaveEndInterval = 2;
      if (this.form.leaveStartDate && this.form.leaveEndDate) {
        await this.daysBetween(this.form.leaveStartDate, this.form.leaveEndDate)
        console.log(this.daysNumber)
        this.form.leaveDuration = this.daysNumber
      }
    },

    async daysBetween(date1, date2) {
      var data = {
        "leaveStartDate":date1,
        "leaveEndDate":date2,
      }
      await getDaysDate(data).then(response => {
        this.daysNumber = response.data.date;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listLeaveReporting(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.tableList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    getUserLists(){
      const Id = this.$store.state.user.id;
      getUserList(Id).then(response => {
        this.userList = response.data.data;
        console.log("userList",this.userList)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openView = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: this.userInfo.id,
        userName: this.userInfo.name,
        orgId: undefined,
        leaveStartDate: undefined,
        leaveStartInterval: undefined,
        leaveEndDate: undefined,
        leaveEndInterval: undefined,
        leaveDuration: undefined,
        examineStatus: "0",
        isAgree: "0",
        hostUserId:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      const Id = this.$store.state.user.id;
      getPostName(Id).then(response => {
        this.form.postName = response.data.postName;
        this.open = true;
        this.title = "新增";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const Id = row.id
      getLeaveReporting(Id).then(response => {
        this.form = response.data;
        // let num = this.form.hostUserId.split(',');
        let num = [];
        let numArr = this.form.hostUserId.split(",")
        numArr.forEach(function (item){
          num.push(parseInt(item));
        })
        console.log("num",num)
        this.$set(this.form,"hostUserId",num)
        this.open = true;
        this.title = "编辑";
      });
    },
    //选择部门
    changDept(e) {
      console.log(e)
      this.orgList.forEach(item => {
        if (item.id == e) {
          this.form.orgName = item.name
        }
      })
    },
    //选择休假类型
    changType(e) {
      console.log(e)
      this.orgList.forEach(item => {
        if (item.id == e) {
          this.form.type = item.name
        }
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form)
          var list = this.form.hostUserId.join(",");
          // 将字符串分割成数组
          const userIdArray = list.split(',');
          // 检查数组中是否同时存在0和其他非0的值
          const containsZero = userIdArray.includes('0');
          const containsOtherValues = userIdArray.some(id => id !== '0');
          if (containsZero && containsOtherValues) {
            this.$modal.msgError("选择’/‘后不能在选择其他人员");
            return ;
          }

          this.form.hostUserId = list;
          var nameList = this.getSelectedUserNameLeave();
          this.form.hostUserName = nameList;

          if (this.form.id != undefined) {
            this.form.examineStatus = 0
            updateLeaveReporting(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLeaveReporting(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    getSelectedUserNameLeave() {
      const selectedUserIdsStr = this.form.hostUserId;
      // 将字符串分割成字符串数组，并将每个元素转换为整数
      const selectedUserIds = selectedUserIdsStr.split(',').map(id => parseInt(id.trim(), 10));

      const selectedUsers = this.userList.filter(option => selectedUserIds.includes(option.userId));

      const selectedUserNames = selectedUsers.map(user => user.userName);

      return selectedUserNames.join(', ');
    },

    /** 查看按钮操作 */
    handleDetails(row) {
      this.reset();
      const Id = row.id
      getLeaveReporting(Id).then(response => {
        this.form = response.data;
        // let num = this.form.hostUserId.split(',');
        let num = [];
        let numArr = this.form.hostUserId.split(",")
        numArr.forEach(function (item){
          num.push(parseInt(item));
        })
        console.log("num",num)
        this.$set(this.form,"hostUserId",num)
        this.openView = true;
        this.title = "详情";
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id;
      this.$modal.confirm('是否确认删除该申请？').then(function () {
        return delLeaveReporting(Ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      exportLeaveReporting(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
        this.downloadFile({
          fileName: `休假报备_${new Date().getTime()}.xlsx`,
          fileData: res,
          fileType: 'application/vnd.ms-excel;charset=utf-8'
        })
      })
    },

  }
};
</script>
