<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">

          <a-col :xl="6" :lg="6" :md="6" :sm="6">
            <a-form-item label="员工名称">
              <a-input placeholder="请输入员工名称" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="6">
            <a-form-item label="部门名称">
              <a-input @click="openModal" placeholder="请点击选择部门" v-model="departNames" readOnly>
                <a-icon slot="prefix" type="cluster" title="部门选择控件" />
                <a-icon v-if="queryParam.dept!=null&&queryParam.dept!=''" slot="suffix" type="close-circle"
                  @click="handleEmpty" title="清空" />
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="6">
            <a-form-item label="日期">
              <a-month-picker valueFormat="YYYY-MM-DD HH:mm:ss" format="YYYY-MM" placeholder="请选择日期"
                v-model="queryParam.ShiftDate" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="6">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQueryst" icon="search">查询</a-button>
              <!-- <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>


    <div>

      <a-button @click="handleAddts()" type="primary" icon="plus" v-has="'UserShift:add'" v-if="isColse">调整</a-button>
      <a-tabs default-active-key="2" @change="callback">
        <a-tab-pane key="2" tab="按班次上下班">
          <a-table bordered rowKey="id" :loading="loading" :data-source="dataSource" :columns="columns"
            :scroll="{ x:300,y:400}" :pagination="ipagination" @change="handleTableChange"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}">
            <template v-for='(dayobject,i) in days' :slot="dayobject.day.getDate()" style="color: #ff6b81">
              <div style="height: 35px;">
                <div style="text-align: center;margin-top: -10px;">
                  <p>{{dayobject.day.getDate()}}</p>
                  <div style="margin-top: -10px;">
                    <p v-if='dayobject.day.getDay()==0'>日</p>
                    <p v-else-if='dayobject.day.getDay()==1'>一</p>
                    <p v-else-if='dayobject.day.getDay()==2'>二</p>
                    <p v-else-if='dayobject.day.getDay()==3'>三</p>
                    <p v-else-if='dayobject.day.getDay()==4'>四</p>
                    <p v-else-if='dayobject.day.getDay()==5'>五</p>
                    <p v-else-if='dayobject.day.getDay()==6'>六</p>
                  </div>
                </div>
              </div>
            </template>

            <span v-for='(d,i) in tpdata' style="margin-left: -6px;" :slot="d" slot-scope="text, record, index">
              <span style="margin-left: -7px;">
                <a-tag color="blue" v-if="text=='休息'">{{text}}</a-tag>
                <a-tag color="#87d068" v-else-if="text!=''&&text!=null">{{text}}</a-tag>
              </span>
            </span>
          </a-table>

          <a-table bordered :data-source="dataSources" :loading="loading" :columns="columnst" :scroll="{ x:300 }"
            :pagination="ipaginations" @change="handleTableChanges">
            <template v-for='(dayobject,i) in days' :slot="dayobject.day.getDate()" style="color: #ff6b81">
              <div style="height: 35px;">
                <div style="text-align: center;margin-top: -10px;">
                  <p>{{dayobject.day.getDate()}}</p>
                  <div style="margin-top: -10px;">
                    <p v-if='dayobject.day.getDay()==0'>日</p>
                    <p v-else-if='dayobject.day.getDay()==1'>一</p>
                    <p v-else-if='dayobject.day.getDay()==2'>二</p>
                    <p v-else-if='dayobject.day.getDay()==3'>三</p>
                    <p v-else-if='dayobject.day.getDay()==4'>四</p>
                    <p v-else-if='dayobject.day.getDay()==5'>五</p>
                    <p v-else-if='dayobject.day.getDay()==6'>六</p>
                  </div>
                </div>
              </div>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="1" tab="固定时间上下班">
          <a-table bordered rowKey="id" :loading="loading" :data-source="dataSource" :columns="columns"
            :scroll="{ x:300 }" :pagination="ipagination" @change="handleTableChange">
            <template v-for='(dayobject,i) in days' :slot="dayobject.day.getDate()" style="color: #ff6b81">
              <div style="height: 35px;">
                <div style="text-align: center;margin-top: -10px;">
                  <p>{{dayobject.day.getDate()}}</p>
                  <div style="margin-top: -10px;">
                    <p v-if='dayobject.day.getDay()==0'>日</p>
                    <p v-else-if='dayobject.day.getDay()==1'>一</p>
                    <p v-else-if='dayobject.day.getDay()==2'>二</p>
                    <p v-else-if='dayobject.day.getDay()==3'>三</p>
                    <p v-else-if='dayobject.day.getDay()==4'>四</p>
                    <p v-else-if='dayobject.day.getDay()==5'>五</p>
                    <p v-else-if='dayobject.day.getDay()==6'>六</p>
                  </div>
                </div>
              </div>
            </template>

          </a-table>
        </a-tab-pane>
        <!-- <a-tab-pane key="3" tab="自由时间上下班">
          <a-table bordered rowKey="id"  :loading="loading" :data-source="dataSource" :columns="columns" :scroll="{ x:300 }"
            :pagination="ipagination" @change="handleTableChange"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}">
            <template v-for='(dayobject,i) in days' :slot="dayobject.day.getDate()" style="color: #ff6b81">
              <div style="height: 35px;">
                <div style="text-align: center;margin-top: -10px;">
                  <p>{{dayobject.day.getDate()}}</p>
                  <div style="margin-top: -10px;">
                    <p v-if='dayobject.day.getDay()==0'>日</p>
                    <p v-else-if='dayobject.day.getDay()==1'>一</p>
                    <p v-else-if='dayobject.day.getDay()==2'>二</p>
                    <p v-else-if='dayobject.day.getDay()==3'>三</p>
                    <p v-else-if='dayobject.day.getDay()==4'>四</p>
                    <p v-else-if='dayobject.day.getDay()==5'>五</p>
                    <p v-else-if='dayobject.day.getDay()==6'>六</p>
                  </div>
                </div>
              </div>
            </template>

          </a-table>
        </a-tab-pane> -->
        <!-- <a-tab-pane key="4" tab="未排班" force-render>
          <a-table bordered :data-source="dataSource" :loading="loading" rowKey="id" :columns="columns" :scroll="{ x:300 }"
            :pagination="ipagination" @change="handleTableChange"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChanges}">
            <template v-for='(dayobject,i) in days' :slot="dayobject.day.getDate()" style="color: #ff6b81">
              <div style="height: 35px;">
                <div style="text-align: center;margin-top: -10px;">
                  <p>{{dayobject.day.getDate()}}</p>
                  <div style="margin-top: -10px;">
                    <p v-if='dayobject.day.getDay()==0'>日</p>
                    <p v-else-if='dayobject.day.getDay()==1'>一</p>
                    <p v-else-if='dayobject.day.getDay()==2'>二</p>
                    <p v-else-if='dayobject.day.getDay()==3'>三</p>
                    <p v-else-if='dayobject.day.getDay()==4'>四</p>
                    <p v-else-if='dayobject.day.getDay()==5'>五</p>
                    <p v-else-if='dayobject.day.getDay()==6'>六</p>
                  </div>
                </div>
              </div>
            </template>

          </a-table>
        </a-tab-pane> -->

      </a-tabs>

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

    <!-- 表单区域 -->
    <attendanceRule-modal ref="modalForm" @ok="modalFormOk"></attendanceRule-modal>
    <depart-window ref="departWindow" @ok="modalFormOks"></depart-window>
    <userShift-modal ref="userShiftModal"></userShift-modal>
  </a-card>
</template>

<script>
  import {
    httpAction,
    getFileAccessHttpUrl,
    getAction,
    deleteAction
  } from '@/api/manage'
  import '@/assets/less/TableExpand.less'
  import AttendanceRuleModal from './modules/AttendanceRuleModal'
  import departWindow from './modules/DepartWindow'
  import {
    JeecgListMixin
  } from '@/mixins/JeecgListMixin'
  import UserShiftModal from './modules/UserShiftModal'
  import moment from "moment"
  export default {
    name: "AttendanceRuleList",
    mixins: [JeecgListMixin],
    components: {
      AttendanceRuleModal,
      UserShiftModal,
      departWindow
    },
    data() {
      return {
        departNames: null,
        queryParam: {
          ShiftDate: moment(new Date()).format('yyyy-MM-DD HH:mm:ss'),
          type: "2",
          dept: null
        },
        description: '打卡规则管理页面',
        tts: false,
        isColse: true,
        tpdata: [],
        currentMonth: new Date().getMonth(),
        currentYear: new Date().getYear(),
        selectedRowKeys: [],
        selectionRows: [],
        // 表头
        dataSource: [],
        dataSources: [],
        columns: [],
        columnst: [],
        days: [],
        visibles: false,
        shiftDate: null,
        show: 1,
        id: null,
        shiftname: "",
        username: "",
        deptlist: null,
        shiftlist: null,
        isShow: true,
        listData: [],
        is: "1",
        ipaginations: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        url: {
          add: "/userShift/userShift/addUserShift",
          userShift: "/userShift/userShift/queryByUser",
          shift: "/shift/shift/lists",
          list: "/sys/user/queryMothByUser",
          moth: "/userShift/userShift/queryMothByUser",
          deptlist: "/sys/sysDepart/listAll",
          delUserShift: '/userShift/userShift/delete',
          lists: "/sys/user/queryMothByCount",
        },
      }
    },
    watch: {
      dataSource: {
        handler(newName, oldName) {
          this.selectedRowKeys=[];
          this.selectionRows=[];
          this.queryMothByCount();
        },
      }
    },
    computed: {
      importExcelUrl: function() {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    created() {
      // this.getListData(null)
      this.initData(null)
      this.queryShift()
      this.queryMothByCount();
    },

    methods: {
      modalFormOks(formData) {
        if (formData.departIdList != null && formData.departIdList.length > 0) {
          for (let i = 0; i < formData.departIdList.length; i++) {
            this.queryParam.dept = formData.departIdList[i].key;
            this.departNames = formData.departIdList[i].title;

          }

        }

      },
      openModal() {
        var ls = [];
        ls.push(this.queryParam.dept);
        this.$refs.departWindow.add(ls, {});
      },
      handleEmpty() {
        this.queryParam.dept = null;
        this.departNames = null;
      },
      handleAddts() {
        if (this.selectedRowKeys.length < 1 && this.queryParam.type == "4") {
          this.$message.warning("请勾选需要排班人员");
          return;
        } else if (this.selectedRowKeys.length < 1 && (this.queryParam.type == "1" || this.queryParam.type == "2" ||
            this.queryParam.type == "3")) {
          this.$message.warning("请勾选需要变更人员");
          return;
        }

        if (this.selectedRowKeys.length > 0 && this.queryParam.type == "4") {
          this.$refs.modalForm.add(this.selectedRowKeys, this.selectionRows);

        } else if (this.selectedRowKeys.length > 0 && (this.queryParam.type == "1" || this.queryParam.type == "2" ||
            this.queryParam.type == "3")) {
          this.$refs.modalForm.edit(this.selectedRowKeys, this.selectionRows);
        }
      },
      onSelectChanges(selectedRowKeys, selectionRows) {
        console.log(selectedRowKeys)
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;

      },
      callback(key) {
        if (key == "1" || key == 1) {
          this.isColse = false;
        } else {
          this.isColse = true;
        }
        this.queryParam.type = key;
        this.selectedRowKeys = [];
        this.selectionRows = [];
        this.$options.methods.searchQuery.call(this)
        this.initData(this.queryParam.ShiftDate)
      },
      searchQueryst() {
        this.queryMothByCount()
        this.$options.methods.searchQuery.call(this)
        this.initData(this.queryParam.ShiftDate)

      },
      handleTableChanges(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipaginations = pagination;
        console.log(pagination)
        this.queryMothByCount();
      },

      initData: function(cur) {
        this.columns = [];
        this.columnst = [];
        this.tpdata = [];
        this.days = [];
        var date
        if (cur) {
          date = new Date(cur)
        } else {
          var now = new Date()
          date = now;
        }
        this.currentDay = date.getDate()
        this.currentYear = date.getFullYear()
        this.currentMonth = date.getMonth() + 1


        var str = this.formatDate(
          this.currentYear,
          this.currentMonth,
          this.currentDay
        )
        this.days.length = 0
        var moth = new Date(str);
        moth.setDate(28)

        moth.setMonth(moth.getMonth() + 1);
        moth.setDate(0);
        this.columns.push({
          title: '名称',
          dataIndex: 'realname',
          width: '100px',
          fixed: 'left'
        })
        this.columnst.push({
          title: '班次名称',
          dataIndex: 'name',
          width: '100px',
          fixed: 'left'
        })
        this.columns.push({
          title: '部门',
          dataIndex: 'deptName',
          width: '140px',
          fixed: 'left'
        })
        if (this.queryParam.type == "1" || this.queryParam.type == "2" || this.queryParam.type == "3") {
          // this.columns.push({
          //   title: '类型',
          //   dataIndex: 'type',
          //   width: '117px',
          //   fixed: 'left',
          //   customRender: function(t, r, index) {
          //     var name = "";
          //     if (t == 1 || t == "1") {
          //       name = "固定时间上下班";
          //     } else if (t == 2 || t == "2") {
          //       name = "按班次上下班";
          //     } else if (t == 3 || t == "3") {
          //       name = "自由时间上下班";
          //     }
          //     return name;
          //   }
          // })
          if (this.queryParam.type == "1") {
            this.columns.push({
              title: '上班时间',
              dataIndex: 'startDate',
              width: '100px',
              fixed: 'left',
              customRender: function(t, r, index) {
                var date = "";
                if (t != null && t != "") {
                  date = moment(new Date(t)).format('HH:mm:ss')
                }
                return date;
              }
            })
            this.columns.push({
              title: '下班时间',
              dataIndex: 'endDate',
              width: '100px',
              fixed: 'left',
              customRender: function(t, r, index) {
                var date = "";
                if (t != null && t != "") {
                  date = moment(new Date(t)).format('HH:mm:ss')
                }
                return date;
              }
            })
          }



          if (this.queryParam.type == "2") {
            for (var i = 1; i <= moth.getDate(); i++) {
              var d = new Date(this.formatDate(this.currentYear, this.currentMonth, i))
              this.tpdata.push(i)
              var dayobjectSelf = {
                width: '49px',
                slots: {
                  title: d.getDate()
                },
                dataIndex: "a" + d.getDate(),
                scopedSlots: {
                  customRender: i
                },

              } // 用一个对象包装Date对象  以便为以后预定功能添加属性

              var dayobjectSelfs = {
                width: '49px',
                slots: {
                  title: d.getDate()
                },
                dataIndex: "b" + d.getDate(),
              }
              var dat = {};
              dat.day = d;

              this.days.push(dat)
              this.columns.push(dayobjectSelf) // 将日期放入data 中的days数组 供页面渲染使用
              this.columnst.push(dayobjectSelfs)
            }
          } else {
            for (var i = 1; i <= moth.getDate(); i++) {
              var d = new Date(this.formatDate(this.currentYear, this.currentMonth, i))
              this.tpdata.push(i)
              var dayobjectSelf = {
                width: '49px',
                slots: {
                  title: d.getDate()
                },
                dataIndex: "a" + d.getDate(),

              } // 用一个对象包装Date对象  以便为以后预定功能添加属性
              var dat = {};
              dat.day = d;

              this.days.push(dat)
              this.columns.push(dayobjectSelf) // 将日期放入data 中的days数组 供页面渲染使用
            }

          }
        } else {
          for (var i = 1; i <= moth.getDate(); i++) {
            var d = new Date(this.formatDate(this.currentYear, this.currentMonth, i))
            this.tpdata.push(i)
            var dayobjectSelf = {
              width: '49px',
              slots: {
                title: d.getDate()
              },
              dataIndex: "a" + d.getDate(),

            } // 用一个对象包装Date对象  以便为以后预定功能添加属性
            var dat = {};
            dat.day = d;

            this.days.push(dat)
            this.columns.push(dayobjectSelf) // 将日期放入data 中的days数组 供页面渲染使用
          }
        }

      },
      queryShift() {
        httpAction(this.url.shift, "", "get").then((res) => {
          if (res.success) {
            this.shiftlist = res.result;
          }
        }).finally(() => {

        })

      },
      queryMothByCount() {
        getAction(this.url.lists, {
          shiftDate: moment(this.queryParam.ShiftDate).format('yyyy-MM-DD HH:mm:ss'),
          userId: this.ipaginations.current,
          shiftId: this.ipaginations.pageSize,
          realname: this.queryParam.name,
          deptid: this.queryParam.dept
        }, "post").then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSources = res.result.records || res.result;
            if (res.result.total) {
              this.ipaginations.total = res.result.total + 1;
            } else {
              this.ipaginationstotal = 0 + 1;
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
        }).finally(() => {

        })

      },
      // 返回 类似 2016-01-02 格式的字符串
      formatDate: function(year, month, day) {
        var y = year
        if (month > 12) {
          y = y + 1;
          month = 1;
        };
        var m = month
        if (m < 10) m = '0' + m
        var d = day
        if (d < 10) d = '0' + d
        return y + '-' + m + '-' + d
      }

    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';

  .month {
    width: 100%;
    color: #333333;
    background: #ffffff;
    margin-top: -20px;
  }

  .month ul {
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: space-between;
    height: 30px;
    list-style-type: none;
  }

  .year-month {
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-top: 10px;
  }

  .choose-month {
    text-align: center;
    font-size: 12px;
  }

  .arrow {
    padding: 15px;
    color: #999999;
  }

  .month ul li {
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 3px;
  }


  .weekdays {
    margin: 0;
    padding: 10px;
    display: flex;
    flex-wrap: wrap;
    color: #999;
    justify-content: space-around;
    background: #ffffff;
  }

  .weekdays li {
    display: inline-block;
    width: 13.6%;
    text-align: center;
  }

  .days {
    padding: 10px;
    background: #ffffff;
    margin: 0;
    display: flex;
    flex-wrap: wrap;
  }

  .ts {
    padding: 20px;
    background: #ffffff;
    margin: 0;
    display: flex;
    flex-wrap: wrap;
  }

  .days li {
    list-style-type: none;
    display: inline-block;
    width: 14.2%;
    text-align: center;
    padding-bottom: 4px;
    padding-top: 5px;
    font-size: 13px;
    color: #000;
    height: 40px;
  }

  .days li .active {
    padding: 8px 10px;
    border-radius: 5%;
    background: #00b8ec;
    color: #fff;

  }

  .days li .other-month {
    padding: 5px;
    color: gainsboro;
  }

  .days li:hover .act {
    padding: 6px 10px;
    border-radius: 50%;
    background: #e1e1e1;
    color: #fff;
  }
</style>
