<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="名称" prop="groupName">
          <el-input
            v-model="queryParams.groupName"
            placeholder="请输入名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="orgName">
          <el-input
            v-model="queryParams.orgName"
            placeholder="请输入部门名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </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"
           
          >新增</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="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="名称" align="center" prop="groupName" />
        <el-table-column label="考勤时间" align="center" prop="attDay" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>每周</span>
            <span  v-if="scope.row.attDay.split(',')[0]==1">一、</span>
            <span  v-if="scope.row.attDay.split(',')[1]==1">二、</span>
            <span  v-if="scope.row.attDay.split(',')[2]==1">三、</span>
            <span  v-if="scope.row.attDay.split(',')[3]==1">四、</span>
            <span  v-if="scope.row.attDay.split(',')[4]==1">五、</span>
            <span  v-if="scope.row.attDay.split(',')[5]==1">六、</span>
            <span  v-if="scope.row.attDay.split(',')[6]==1">日</span>
          </template>
        </el-table-column>
        <el-table-column label="上班时间" align="center" prop="toWorkTime" :show-overflow-tooltip="true" />
        <el-table-column label="下班时间" align="center" prop="offWorkTime" :show-overflow-tooltip="true" />
        <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </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"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(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="850px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="考勤组名称" prop="groupName">
                <el-input v-model="form.groupName" placeholder="请输入考勤组名称" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="参与考勤人员" prop="checkList">
                  <treeselect v-model="form.checkList"  :multiple="true" :flat="true" :options="personOptions" :normalizer="normalizer" placeholder="选择部门负责人" @select="handleSelect"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="考勤类型" prop="attType">
                <el-radio-group v-model="form.attType" @change="changeRadio">
                  <el-radio
                    v-for="dict in typeList"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="考勤时间" prop="attDays">
                <el-checkbox-group v-model="form.attDays">
                  <el-checkbox v-for="item in attDayList" :key="item.id"
                    :label="item.id">{{item.label}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="上班时间" prop="toWorkTime">
                <el-time-select
                  v-model="form.toWorkTime"
                  :picker-options="{
                    start: '00:00',
                    step: '00:15',
                    end: '23:59'
                  }"
                  placeholder="选择时间">
                </el-time-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下班时间" prop="offWorkTime">
                <el-time-select
                  v-model="form.offWorkTime"
                  :picker-options="{
                    start: '00:00',
                    step: '00:15',
                    end: '23:59'
                  }"
                  placeholder="选择时间">
                </el-time-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="迟到、早退设置" prop="lateMinute">
                 迟到<el-input v-model="form.lateMinute" maxlength="4" style="width: 100px;"/>分钟不计迟到,早退<el-input v-model="form.leaveMinute" maxlength="4" style="width: 100px;"/>分钟不计早退
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="旷工设置" prop="absenteeismLateMinute">
                 迟到<el-input v-model="form.absenteeismLateMinute" maxlength="4" style="width: 100px;"/>分钟即为旷工,早退<el-input v-model="form.absenteeismLeaveMinute" maxlength="4" style="width: 100px;"/>分钟即为旷工
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="出入异常设置" prop="entryAbnormalMinute">
                <el-input v-model="form.entryAbnormalMinute" maxlength="4" style="width: 100px;"/>分钟内连续打卡进出即为出入异常
              </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>
    </div>
  </template>
  
  <script>
  import { listAttGroup,getAttGroup,delAttGroup,addAttGroup,updateAttGroup,selectOrgList } from "@/api/setting/rules";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
    name: "rules",
    dicts: ['sys_normal_disable'],
    components: { Treeselect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        userList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          groupName: undefined,
          orgName: undefined
        },
        personOptions:[],
        typeList:[{value:'0',label:'固定班制'},{value:'1',label:'自由工时'}],
        attDayList:[{id:0,label:'周一'},{id:1,label:'周二'},{id:2,label:'周三'},{id:3,label:'周四'},{id:4,label:'周五'},{id:5,label:'周六'},{id:6,label:'周日'}],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          groupName: [
            { required: true, message: "名称不能为空", trigger: "blur" }
          ],
          attDays: [
            { required: true, message: "考勤时间不能为空", trigger: "blur" }
          ],
          toWorkTime: [
            { required: true, message: "上班时间不能为空", trigger: "blur" }
          ],
          offWorkTime: [
            { required: true, message: "下班时间不能为空", trigger: "blur" }
          ]
        }
      };
    },
    created() {
      this.selectOrgList();
      this.getList();
    },
    methods: {
      selectOrgList() { 
        selectOrgList().then(res => {
            console.log(res)
            this.personOptions=this.changeData(res.data);
            // // this.personOptions = this.handleTree(response.data, "id");
            // console.log(this.personOptions)
          }
        );
      },
      //数据操作
      changeData(data)  { // 存在子集就不让禁止，父级让禁止
        data.map(item => {
          if (!item.disabled||item.children.length>0) {
            item.isDisabled = false
          } else if (item.disabled&&item.children.length==0){
            item.isDisabled = true
          }
          item.children && item.children.length > 0 && this.changeData(item.children);
        })
        return data;
      },
      handleSelect(value, instanceId) { 
        console.log('Selected:', value);
        // 在这里处理选择事件 
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      changeRadio(v){
        console.log(v)
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        listAttGroup(this.queryParams).then(response => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          groupName: undefined,
          attType: "0",
          checkList: [],
          attDays: [0,1,2,3,4],
          attDay: undefined,
          toWorkTime:"08:30:00",
          offWorkTime:"17:30:00",
          lateMinute: undefined,//迟到分钟
          leaveMinute: undefined,//早退分钟
          absenteeismLateMinute: undefined,//旷工迟到分钟
          absenteeismLeaveMinute: undefined,//旷工早退分钟
          entryAbnormalMinute: undefined,//出入异常时间



        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "新增";
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.groupId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const groupId = row.groupId || this.ids
        getAttGroup(groupId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "编辑";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        console.log(this.form)
        this.$refs["form"].validate(valid => {
          if (valid) {
            let arr=[0,0,0,0,0,0,0]
            this.form.attDays.forEach(item=>{arr[item]=1}) 
            this.form.attDay=arr.join(",")
            console.log(this.form)
        //     if (this.form.groupId != undefined) {
        //       updateAttGroup(this.form).then(response => {
        //         this.$modal.msgSuccess("修改成功");
        //         this.open = false;
        //         this.getList();
        //       });
        //     } else {
        //       addAttGroup(this.form).then(response => {
        //         this.$modal.msgSuccess("新增成功");
        //         this.open = false;
        //         this.getList();
        //       });
        //     }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const groupIds = row.groupId || this.ids;
        this.$modal.confirm('是否确认删除编号为"' + groupIds + '"的数据项？').then(function() {
          return delAttGroup(groupIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/dict/type/export', {
          ...this.queryParams
        }, `type_${new Date().getTime()}.xlsx`)
      },
 
    }
  };
  </script>