<template>
  <a-card :bordered="false" style="background-color:transparent">
    <!-- table区域-begin -->
      <div class="ant-alert ant-alert-info" style="margin-bottom: 10px;margin-top: -40px;">
        <!--<i class="anticon anticon-info-circle ant-alert-icon"></i> 
        已选择 <a style="font-weight: 600">{{selectedRowKeys.length }}</a>项
         <a style="margin-left: 24px" @click="onClearSelected">清空</a> -->
       
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        姓名: <a style="margin-right: 40px"> {{userName }}</a>
        
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        部门: <a style="margin-right: 40px">{{deptName}}</a>
        
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        员工类型: <a style="margin-right: 40px">{{userType}}</a>
        
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        月份: 
        <!-- <a style="font-weight: 600;margin-right: 6px" @click="onClearSelected">  <  </a> -->
        <a-month-picker format="YYYY-MM" placeholder="请输入考勤月份" v-model="headMonth" @change="onDateChange"/>
        <!-- <a style="font-weight: 600;margin-left: 6px" @click="onClearSelected"> > </a> -->
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        <a style="margin-left: 40px" @click="errorInfoShow()">异常打卡</a>
       <i class="anticon anticon-info-circle ant-alert-icon"></i>
       <a style="margin-left: 40px" @click="jiaBanInfoShow()">加班打卡</a>
       <i class="anticon anticon-info-circle ant-alert-icon"></i>
       <a-dropdown style="margin-left: 40px" v-has="'viewClockUserInfo:more'">
         <a class="ant-dropdown-link">
           更多操作 <a-icon type="down"/>
         </a>
         <!-- 123-->
         <a-menu slot="overlay">
           <a-menu-item v-has="'viewClockUserInfo:fuxin'">
             <a-popconfirm title="确定对所选记录付薪吗?" @confirm="() => handleInfo('1')">
               <a>付薪</a>
             </a-popconfirm>
           </a-menu-item>
           <a-menu-item v-has="'viewClockUserInfo:tiaoxiu'">
             <a-popconfirm title="确定对所选记录累计调休吗?" @confirm="() => handleInfo('2')">
               <a>累计调休</a>
             </a-popconfirm>
           </a-menu-item>
           <a-menu-item v-has="'viewClockUserInfo:hulue'">
             <a-popconfirm title="确定对所选记录忽略吗?" @confirm="() => handleInfo('3')">
               <a>忽略</a>
             </a-popconfirm>
           </a-menu-item>
         </a-menu>
       </a-dropdown>
       <a style="margin-left: 40px" @click="handleExportXlsBegin('员工考勤信息')">导出</a>
       <i class="anticon anticon-info-circle ant-alert-icon"></i>
      </div>

      <a-table
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        ref="table"
        size="middle"
        bordered
        rowKey="viewDate"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange" :scroll="{ x: 1600, y: 550 }">

        <span slot="ShiftTime" slot-scope="text, record, index">
           {{record.shiftRealTimeS}} - {{record.shiftRealTimeX}}
            <span v-if="record.shiftRealTime2S != null "><br/>{{record.shiftRealTime2S}} - {{record.shiftRealTime2X}}</span>
        </span>
        <span slot="customTime" slot-scope="text, record, index">
           <span v-if="text != null ">{{text.slice(10)}}</span>
        </span>
        
        <span slot="customDuration" slot-scope="text, record, index">
          <!-- <a-tag @click="workInfo(record)" color="pink" v-if="record.workOvertime != null && record.workOvertime > 0 ">
          {{text}}
          </a-tag>
          <a @click="workInfo(record)" v-else>{{text}}</a> -->
          <span v-if="record.setInfo > 0 ">
            <a-tag title="点击查看加班详情" @click="workInfo(record)" color="pink" >{{text}}</a-tag> 
          </span>
          <span v-if="record.setInfo == 0 ">
            <a-tag title="点击查看加班详情" @click="workInfo(record)" color="#87d068" >{{text}}</a-tag> 
          </span>
        </span>
        
        <a-badge slot="shiftType" slot-scope="text, record, index">
          <!-- ruleType 上班类型 1.固定时间上下班，2.按班次上下班，3.自由上下班 -->
          
          <a-tag color="pink" v-if="record.showState == '1'">
            异常
          </a-tag>
          <a-tag color="#87d068" v-if="record.showState == '2'">
           正常
          </a-tag>
           <a-icon v-if="record.showState == '2'" title="该员工在未排班或休息班打卡" slot="count" type="exclamation-circle" style="color: #f52b02" />
          
          <a-tag color="#87d068" v-if="record.showState == '0'">
            正常
          </a-tag>

        </a-badge>
        
        <span slot="action" slot-scope="text, record">
          <!-- <a v-has="'viewClockUserInfo:jiaozhun'" @click="handleEdit(record)">校准</a> -->
          <a v-has="'viewClockUserInfo:jiaozhun'" @click="showModal(record)">校准</a>
         <!-- <a-popconfirm v-has="'viewClockUserInfo:jiaozhun'"  title="确定忽略此异常吗?" @confirm="() => errorInfo(record)">
            <a>校准</a>
          </a-popconfirm>-->
          
          <a-divider type="vertical"/>

          <a-dropdown v-has="'viewClockUserInfo:more'">
            
            <a class="ant-dropdown-link">
              更多 <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item v-has="'viewClockUserInfo:fuxin'">
                <a-popconfirm title="确定付薪吗?" @confirm="() => fuXinInfo('2','1',record)">
                  <a>付薪</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item v-has="'viewClockUserInfo:tiaoxiu'">
                <a-popconfirm title="确定累计调休吗?" @confirm="() => fuXinInfo('2','2',record)">
                  <a>累计调休</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item v-has="'viewClockUserInfo:hulue'">
                <a-popconfirm title="确定忽略吗?" @confirm="() => fuXinInfo('2','3',record)">
                  <a>忽略</a>
                </a-popconfirm>
              </a-menu-item>
          
            </a-menu>
          </a-dropdown>
        </span>


      </a-table>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <Jiao-Zhun-Modal ref="modalForm" @ok="modalFormOk"></Jiao-Zhun-Modal>
    <Select-User-Modal ref="selectUserModal" @selectFinished="selectOK"></Select-User-Modal>
    <dept-role-user-modal ref="deptRoleUser"></dept-role-user-modal>
    <a-modal width="1200px"
          v-model="modal2Visible" title="加班信息详情" :footer="null"
          centered @ok="() => (modal2Visible = false)" >
           <a-table :columns="columns2" :data-source="data" rowKey="id">
             
             <span slot="action" slot-scope="text, record">
             
               <a-dropdown v-has="'viewClockUserInfo:more'">
                 
                 <a class="ant-dropdown-link">
                   更多 <a-icon type="down"/>
                 </a>
                 <a-menu slot="overlay">
                   <a-menu-item v-has="'viewClockUserInfo:fuxin'">
                     <a-popconfirm title="确定付薪吗?" @confirm="() => fuXinInfo('1','1',record)">
                       <a>付薪</a>
                     </a-popconfirm>
                   </a-menu-item>
                   <a-menu-item v-has="'viewClockUserInfo:tiaoxiu'">
                     <a-popconfirm title="确定累计调休吗?" @confirm="() => fuXinInfo('1','2',record)">
                       <a>累计调休</a>
                     </a-popconfirm>
                   </a-menu-item>
                   <a-menu-item v-has="'viewClockUserInfo:hulue'">
                     <a-popconfirm title="确定忽略吗?" @confirm="() => fuXinInfo('1','3',record)">
                       <a>忽略</a>
                     </a-popconfirm>
                   </a-menu-item>
                 </a-menu>
               </a-dropdown>
             </span>
           </a-table>
    </a-modal>
    
    <a-modal
          title="校准忽略本次异常"
          :visible="visible"
          :confirm-loading="confirmLoading"
          @ok="handleOk"
          @cancel="handleCancel"
        >
          <a-input placeholder="请填写忽略原因" v-model="errorText"></a-input>
    </a-modal>
  </a-card>
</template>

<script>
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import {getAction, postAction, deleteAction,putAction} from '@/api/manage'
  import SelectUserModal from '../modules/SelectUserModal'
  import JiaoZhunModal from './JiaoZhunModal'
  import DeptRoleUserModal from '../modules/DeptRoleUserModal'
  import moment from 'moment';
  import 'moment/locale/zh-cn';
  import {
    fuXinInfo
  } from '@/api/api'
  
  export default {
    name: "DeptUserInfo",
    mixins: [JeecgListMixin],
    components: {
      DeptRoleUserModal,
      SelectUserModal,
      JiaoZhunModal
    },
    data() {
      return {
        errorViewDate:'',
        errorSt:'',
        errorUserId:'',
        errorText: '',//校准弹框属性
        visible: false,//校准弹框属性
        confirmLoading: false,//校准弹框属性
        durationCommitDate:'',//加班申请时间
        durationBeginDate:'',//加班开始时间
        durationEndDate:'',//加班结束时间
        duration:'',//加班时长
        demo:'',//加班事由
        modal2Visible: false,
        moment,
        description: '员工考勤信息',
        userName:'',//标题员工姓名
        deptName:'',//标题员工部门
        userType:'',//标题员工类型
        headMonth:'',//标题选择月份
        newMonth:'',//更改时选择的月份
        currentDeptId: '',
        data : [],//加班信息弹框
        columns2:[{
          title: '加班申请时间',
          align: "center",
          dataIndex: 'commitDate'
        },{
          title: '加班开始时间',
          align: "center",
          dataIndex: 'beginDate'
        },{
          title: '加班结束时间',
          align: "center",
          dataIndex: 'endDate'
        },{
          title: '加班时长',
          align: "center",
          dataIndex: 'duration'
        },{
          title: '加班事由',
          align: "center",
          dataIndex: 'demo'
        },{
          title: '处理方式',
          align: "center",
          dataIndex: 'setInfo'
        },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: {customRender: 'action'},
            align: "center",
            width: 120
          }],
        // 表头
        columns: [{
            title: '日期',
            align: "center",
            dataIndex: 'viewDate', fixed: 'left', width: 100
          },
          {
            title: '星期',
            align: "center",
            dataIndex: 'weekDate'
          },
          {
            title: '班次',
            align: "center",
            dataIndex: 'name'
          },
          {
            title: '班次时间',
            align: "center",
            scopedSlots: {
              customRender: 'ShiftTime'
            }
          },
          {
            title: '状态',
            align: "center",
            scopedSlots: {customRender: 'shiftType'},
          },
          {
            title: '最早',
            align: "center",
            dataIndex: 'gotoTime',
            scopedSlots: {
              customRender: 'customTime'
            }
          },
          {
            title: '最晚',
            align: "center",
            dataIndex: 'closingTime',
            scopedSlots: {
              customRender: 'customTime'
            }
          },{
            title: '上班1',
            align: "center",
            dataIndex: 'oneTime',
            scopedSlots: {
              customRender: 'customTime'
            }
          },
          {
            title: '下班1',
            align: "center",
            dataIndex: 'twoTime',
            scopedSlots: {
              customRender: 'customTime'
            }
          },{
            title: '上班2',
            align: "center",
            dataIndex: 'threeTime',
            scopedSlots: {
              customRender: 'customTime'
            }
          },
          {
            title: '下班2',
            align: "center",
            dataIndex: 'fourTime',
            scopedSlots: {
              customRender: 'customTime'
            }
          },
          {
            title: '打卡次数',
            align: "center",
            dataIndex: 'attendanceCount'
          },  
          // {
          //   title: '加班申请',
          //   align: "center",
          //   dataIndex: 'demo',
          //   width: 200
          // },
          {
            title: '加班时间',
            align: "center",
            dataIndex: 'duration',
            width: 100,
            scopedSlots: {
              customRender: 'customDuration'
            }
          },
          {
            title: '校准人',
            align: "center",
            dataIndex: 'jzBy'
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: {customRender: 'action'},
            align: "center",
            width: 120
          }],
        url: {
          exportXlsUrl: '/viewClockIn/viewClockIn/exportXls',
          handleInfo: '/viewClockIn/viewClockIn/handleInfo',
          errorInfo: '/viewClockIn/viewClockIn/errorInfo',
          getJiaBan: '/workOvertime/workOvertime/getJiaBan',
          list: '/viewClockIn/viewClockIn/list',
          // list: "/sys/user/departUserList",
          edit: "/sys/user/editSysDepartWithUser",
          delete: "/sys/user/deleteUserInDepart",
          deleteBatch: "/sys/user/deleteUserInDepartBatch",
        }
      }
    },
    created() {
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;
      // let dd = new Date().getDate();
      this.headMonth = yy+"-"+mm;
    },

    methods: {
        handleExportXlsBegin(name){
          if(this.userName == '' || this.userName == null){
            this.$message.warning("请选择要导出的人员姓名");
            return;
          }
          if(this.headMonth == '' && this.newMonth == null){
            this.$message.warning("请选择要导出的月份");
            return;
          }
          this.queryParam.userType=this.userType;
          this.handleExportXls(name);
        },
        handleInfo(st){
          if(this.selectedRowKeys.length < 1){
            this.$message.warning("您没有选择任何数据");
            return;
          }
          let that = this;
          //st：1付薪 2累计调休 3忽略
          let ids = "";
          let username = "";
          let dataSource = this.dataSource;
          // console.log("-===="+this.dataSource);
          let userIds = "";
          this.selectUserRows = [];
          for (let i = 0, len = dataSource.length; i < len; i++) {
            if (this.selectedRowKeys.includes(dataSource[i].viewDate)) {
              
              if(dataSource[i].duration == null || dataSource[i].duration == ''){
                this.$message.warning(dataSource[i].viewDate+"该员工当日没有加班申请信息，请勿此操作");
                return;
              }
             username = dataSource[i].username;
             ids += dataSource[i].viewDate + ",";
            }
          }

          putAction(this.url.handleInfo, {viewDate:ids,st:st,username:username}).then((res) => {
            if (res.success) {
              that.$message.success("操作成功");
              that.loadData();
            } else {
              that.$message.warning(res.message);
              that.loadData();
            }
          }).finally(() => {
            that.selectedRowKeys = [];
          })
        },
        errorInfoShow(){
          this.queryParam.showState=1;
          this.loadData(1);
          this.queryParam.showState=null;
         
        },
        jiaBanInfoShow(){
          this.queryParam.duration=1;
          this.loadData(1);
          this.queryParam.duration=null;
        },
        showModal(record) {
          this.errorViewDate = record.viewDate;
          this.errorUserId = record.userId;
          this.errorSt = record.errorState;
          this.errorText = record.errorText;
          this.visible = true;
        },
        handleOk(e) {
          if(this.errorSt == 0){
             this.$message.warning("已校准过，无需再次校准");
             return;
          }
          if(this.errorText == null || this.errorText == ''){
             this.$message.warning("请填写忽略原因");
             return;
          }
          let that = this;
          this.confirmLoading = true;
          putAction(this.url.errorInfo, {viewDate:this.errorViewDate,userId:this.errorUserId,errorText:this.errorText}).then((res) => {
            if (res.success) {
              that.$message.success("操作成功");
              that.loadData();
            } else {
              that.$message.warning(res.message);
              that.loadData();
            }
          }).finally(() => {
            this.confirmLoading = false;
            this.visible = false;
          })
        },
        handleCancel(e) {
          console.log('Clicked cancel button');
          this.visible = false;
        },
      onDateChange: function (value, dateString) {
        this.newMonth = dateString;
        this.$emit('clearSelectedDepartKeys');
        // this.userName = e.node.dataRef.title;
        this.queryParam.mDate=dateString;
        this.loadData(1);
        // console.log(value+"------------"+dateString);
       
      },
      searchReset() {
        this.queryParam = {}
        this.loadData(1);
      },
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return
        }
        
        if (!this.userName) {
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        //if (this.currentDeptId === '') return;
        let params = this.getQueryParams();//查询条件
        
        params.depId = this.currentDeptId;
        // params = {'endViewDate':'userName'}
        //  console.log("============="+params.userName);
        getAction(this.url.list, params).then((res) => {
          if (res.success && res.result) {
            this.dataSource = res.result.records;
            this.ipagination.total = res.result.total;
          }
        })
      },
      batchDel: function () {

        if (!this.url.deleteBatch) {
          this.$message.error("请设置url.deleteBatch属性!")
          return
        }
        if (!this.currentDeptId) {
          this.$message.error("未选中任何部门，无法取消部门与用户的关联!")
          return
        }

        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        } else {
          var ids = "";
          for (var a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ",";
          }
          var that = this;
          console.log(this.currentDeptId);
          this.$confirm({
            title: "确认取消",
            content: "是否取消用户与选中部门的关联?",
            onOk: function () {
              deleteAction(that.url.deleteBatch, {depId: that.currentDeptId, userIds: ids}).then((res) => {
                if (res.success) {
                  that.$message.success("删除用户与选中部门关系成功！");
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.message);
                }
              });
            }
          });
        }
      },
      handleDelete: function (id) {
        if (!this.url.delete) {
          this.$message.error("请设置url.delete属性!")
          return
        }
        if (!this.currentDeptId) {
          this.$message.error("未选中任何部门，无法取消部门与用户的关联!")
          return
        }

        var that = this;
        deleteAction(that.url.delete, {depId: this.currentDeptId, userId: id}).then((res) => {
          if (res.success) {
            that.$message.success("删除用户与选中部门关系成功！");
            if (this.selectedRowKeys.length>0){
               for(let i =0; i<this.selectedRowKeys.length;i++){
                   if (this.selectedRowKeys[i] == id){
                     this.selectedRowKeys.splice(i,1);
                     break;
                   }
               }
            }
            that.loadData();
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      open(selectedKeys, e) {
        
        if(e.node.dataRef.orgType == 1 || e.node.dataRef.orgType == 2 || e.node.dataRef.orgType == 3){
          // this.$message.warn("点击左侧加减号，展开或者收起菜单!")
          return;
        }
        this.queryParam = {}
        let arr = e.node.dataRef.title.split('（');//姓名
        let arr2 = e.node.$parent.title.split('（');//上级部门
        this.userName = arr[0];//e.node.dataRef.title;
        this.deptName = arr2[0];//e.node.$parent.title;
        this.userType = e.node.dataRef.orgType;//员工类型
        this.queryParam.userName= arr[0];//e.node.dataRef.title;
        this.queryParam.mDate=moment(this.headMonth).format('YYYY-MM');
        this.loadData(1);
      },
      clearList() {
        this.currentDeptId = '';
        this.dataSource = [];
      },
      hasSelectDept() {
        if (this.currentDeptId == '') {
          this.$message.error("请选择一个部门!")
          return false;
        }
        return true;
      },
      handleAddUserDepart() {
        if (this.currentDeptId == '' ) {
          this.$message.error("请选择一个部门!")
        } else {
          this.$refs.selectUserModal.visible = true;
        }
      },
      handleEdit: function (record) {
        this.$refs.modalForm.title = "校准";
        this.$refs.modalForm.departDisabled = true;
        this.$refs.modalForm.disableSubmit = false;
        this.$refs.modalForm.startDate = record.gotoTime;
        this.$refs.modalForm.endDate = record.closingTime;
        if(record.gotoTime == null || record.gotoTime == ''){
          this.$refs.modalForm.startDate = record.viewDate;
        }
        if(record.closingTime == null || record.closingTime == ''){
          this.$refs.modalForm.endDate = record.viewDate;
        }
        this.$refs.modalForm.startDateYs = record.gotoTime;
        this.$refs.modalForm.endDateYs = record.closingTime;
        this.$refs.modalForm.jzTime = record.jzTime;
        this.$refs.modalForm.jzBy = record.jzBy;
        
        this.$refs.modalForm.viewDate = record.viewDate;
        this.$refs.modalForm.username = record.userId;
        this.$refs.modalForm.setInfo = record.setInfo;
        this.$refs.modalForm.add(record);
      },
      handleAdd: function () {
        if (this.currentDeptId == '') {
          this.$message.error("请选择一个部门!")
        } else {
          this.$refs.modalForm.departDisabled = true;
          this.$refs.modalForm.userDepartModel.departIdList = [this.currentDeptId];  //传入一个部门id
          this.$refs.modalForm.add();
          this.$refs.modalForm.title = "新增";
        }
      },
      selectOK(data) {
        let params = {};
        params.depId = this.currentDeptId;
        params.userIdList = [];
        for (var a = 0; a < data.length; a++) {
          params.userIdList.push(data[a]);
        }
       
        postAction(this.url.edit, params).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.loadData();
          } else {
            this.$message.warning(res.message);
          }
        })
      },
      errorInfo(record){//校准
        if(record.errorState == 0){
           this.$message.warning("已校准过，无需再次校准");
           return;
        }
        let that = this;
        putAction(this.url.errorInfo, {viewDate:record.viewDate,userId:record.userId}).then((res) => {
          if (res.success) {
            that.$message.success("操作成功");
            that.loadData();
          } else {
            that.$message.warning(res.message);
            that.loadData();
          }
        }).finally(() => {
              
        })
        
      },
      fuXinInfo(w,st,record){//薪资操作
      
          // w  1:弹框中方法，2列表中方法
          // st 1付薪，2累计调休，3忽略
          // if(record.setInfo != '' && record.setInfo != null){
          //    this.$message.warning("已设置过，不能再次设置");
          //    return;
          // }
          if(record.duration == '' || record.duration == null){
             this.$message.warning("该员工当日没有加班申请信息");
             return;
          }
          let userId = null;
          if(record.userId == '' || record.userId == null){
            userId = record.person;
          }else{
            userId = record.userId;
          }
          let that = this;
          fuXinInfo({viewDate:record.viewDate,viewDate1:record.beginDate,userId:userId,pkId:record.id,st:st,w:w}).then((res) => {
            if (res.success) {
              that.$message.success("已成功设置");
              that.loadData();
            } else {
              that.$message.warning(res.message);
              that.loadData();
            }
          });
          that.modal2Visible = false;
      },
      workInfo(record){//点击加班时间事件
      
        let that = this;
        
        putAction(this.url.getJiaBan, {viewDate:record.viewDate,username:record.username}).then((res) => {
          that.data = res;
        }).finally(() => {
           that.modal2Visible = true;
        })
     
      }
    }
  }
</script>
<style scoped>
  /** Button按钮间距 */
  .ant-btn {
    margin-left: 3px
  }

  .ant-card {
    margin-left: -30px;
    margin-right: -30px;
  }

  .table-page-search-wrapper {
    margin-top: -16px;
    margin-bottom: 16px;
  }
</style>