<template>
  <a-card :bordered="false">
    <!-- 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> -->
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange">

        <span slot="ShiftTime" slot-scope="text, record, index">
           {{record.shiftRealTimeS}} - {{record.shiftRealTimeX}}
        </span>
        <span slot="customTime" slot-scope="text, record, index">
           {{text.slice(10)}}
        </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>
        
        <span slot="shiftType" slot-scope="text, record, index">
          <!-- ruleType 上班类型 1.固定时间上下班，2.按班次上下班，3.自由上下班 -->
           <!--<span v-if="record.latetimeS < 0 || record.latetimeX > 0 || record.shiftRealTimeS == '' || record.shiftRealTimeS == null">
            异常 <a>{{record.setInfo}}</a>
          </span>
          <span v-else>正常 <a>{{record.setInfo}}</a></span> -->
          
          <a-tag color="pink" v-if="record.latetimeS < 0 || record.latetimeX > 0 
          || (record.ifwork !=0 && record.attendanceCount < 2 && record.name != null)
          || (record.name != null && record.name != '' && (record.gotoTime == null || record.gotoTime == ''))
          || record.duration != null
          && (record.setInfo == '' || record.setInfo == null)">
          异常
          </a-tag>
          <a-tag color="#87d068" v-else>正常</a-tag>
          <a>{{record.setInfo}}</a>
        </span>
        
        <span slot="action" slot-scope="text, record">
          <a v-has="'viewClockUserInfo:jiaozhun'" @click="handleEdit(record)">校准</a>

          <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>
                <a-popconfirm title="确定付薪吗?" @confirm="() => fuXinInfo('1',record)">
                  <a>付薪</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定累计调休吗?" @confirm="() => fuXinInfo('2',record)">
                  <a>累计调休</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定忽略吗?" @confirm="() => fuXinInfo('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
          v-model="modal2Visible" title="加班信息详情" :footer="null"
          centered @ok="() => (modal2Visible = false)" >
          <h4>加班申请时间 ： {{durationCommitDate}}</h4>
          <h4>加班开始时间 ： {{durationBeginDate}}</h4>
          <h4>加班结束时间 ： {{durationEndDate}}</h4>
          <h4>加班时长 ： {{duration}}</h4>
          <h4>加班事由 ： {{demo}}</h4>
    </a-modal>
  </a-card>
</template>

<script>
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import {getAction, postAction, deleteAction} 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 {
        durationCommitDate:'',//加班申请时间
        durationBeginDate:'',//加班开始时间
        durationEndDate:'',//加班结束时间
        duration:'',//加班时长
        demo:'',//加班事由
        modal2Visible: false,
        moment,
        description: '员工考勤信息',
        userName:'',//标题员工姓名
        deptName:'',//标题员工部门
        userType:'',//标题员工类型
        headMonth:'',//标题选择月份
        newMonth:'',//更改时选择的月份
        currentDeptId: '',
        // 表头
        columns: [{
            title: '日期',
            align: "center",
            dataIndex: 'viewDate'
          },
          {
            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: '打卡次数',
            align: "center",
            dataIndex: 'attendanceCount'
          },  
          {
            title: '加班申请',
            align: "center",
            dataIndex: 'demo',
            width: 200
          },
          {
            title: '加班时间',
            align: "center",
            dataIndex: 'duration',
            width: 100,
            scopedSlots: {
              customRender: 'customDuration'
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: {customRender: 'action'},
            align: "center",
            width: 120
          }],
        url: {
          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: {
      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;
        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);
          }
        })
      },
      fuXinInfo(st,record){
          // 1付薪，2累计调休，3忽略
          if(record.setInfo != '' && record.setInfo != null){
             this.$message.warning("已设置过，不能再次设置");
             return;
          }
          if(record.demo == '' || record.demo == null){
             this.$message.warning("该员工当日没有加班申请信息");
             return;
          }
          let that = this;
          fuXinInfo({viewDate:record.viewDate,userId:record.userId,st:st}).then((res) => {
            if (res == 'true') {
              that.$message.success("已成功设置");
              that.loadData();
            } else {
              that.$message.warning(res);
              that.loadData();
            }
          });
               
      },
      workInfo(record){
         this.modal2Visible = true;
         this.durationCommitDate = record.commitDate;//加班申请时间
         this.durationBeginDate = record.durationBeginDate;//加班开始时间
         this.durationEndDate = record.durationEndDate;//加班结束时间
         this.duration = record.duration;//加班时长
         this.demo = record.demo;//加班事由   
      }
    }
  }
</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>