<template>
   <div style="background-color: #fff; padding:20px;" class="boxMinHeight">
    <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list flex-box-ce">
      <el-button
        class="first-element-btn"
        v-if="profile.employee_detail.role_list.findIndex(item => item.name == 'admin' || 'point_manager' || 'creator') >= 0"
        :disabled="multipleSelection.length < 1"
        @click="confirmMultipleDelete"
        type="primary"
        plain
      >
        批量删除
      </el-button>
      <el-button @click="toDetailPage(0, $event)" type="primary" style="margin-right:10px;">创建考勤组</el-button>
      <el-select v-model="filter.employee_id" clearable filterable placeholder="请输入或选择人员" @change="employeSearch">
        <el-option v-for="item in employee_map" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <div class="gap-right-8" style="display:inline-block; width:220px;margin-left: 10px;">
        <el-input placeholder="输入关键词查找" ref="search-bar" v-model="filter.keywords" class="input-with-select" @keyup.enter.native="onFilterChanged">
          <el-button slot="append" icon="el-icon-search" @click="onFilterChanged"></el-button>
        </el-input>
      </div>
      <div class="flex-1"></div>
      <span class="blue cursor"  @click="$openUrl(13)"><i class="el-icon-question" style="padding-right: 5px;font-size: 14px;position: relative;top: 1px;"></i>考勤组如何设置</span>
    </div>

    <el-table @selection-change="handleSelectionChange" v-loading="loading" ref="multipleTable" :data="tableData" :border="false" tooltip-effect="dark" style="width: 100%">
      <el-table-column type="selection"  width="50" v-if="profile.employee_detail.role_list.findIndex(item => item.name == 'admin' || 'point_manager' || 'creator') >= 0"></el-table-column>
      <el-table-column prop="name" label="名称" :filterMultiple="false"></el-table-column>
      <el-table-column prop="type" label="类型" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 0">固定班制</span>
          <span v-if="scope.row.type == 1">排班制</span>
          <span v-if="scope.row.type == 2">自由上下班</span>
        </template>
      </el-table-column>

      <el-table-column label="班次" width="300" header-align="center" align="left">
        <template slot-scope="scope">
          <div v-for="(items, index) in scope.row.schedules" :key="index">
            <div v-for="(item, index) in items.config.split(',')" :key="index" style="margin:8px 0">
              <div style="vertical-align: top; display: table-cell;font-size:15px;font-weight:bold;">
                打卡时段：
                <span style="color:#409EFF;font-weight:bold;">{{ item.split('-')[0] }}-{{ item.split('-')[3] }}</span>
              </div>
              <div>
                <span>{{ item.split('-')[0] }}</span>
                最早打卡时间
                <span>{{ item.split('-')[3] }}</span>
                最晚打卡时间
              </div>
              <div>
                <span>{{ item.split('-')[1] }}</span>
                上班打卡时间
                <span>{{ item.split('-')[2] }}</span>
                下班打卡时间
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="left" label="操作" width="200">
        <template slot-scope="scope">
          <div>
            <el-button type="text" style="color:#409EFF !important;" @click="toDetailPage(scope.row.id, $event)">修改</el-button>
            <el-button
              style="color:#f56c6c !important;"
              v-if="profile.employee_detail.role_list.findIndex(item => item.name == 'admin' || 'point_manager' || 'creator') >= 0"
              type="text"
              @click="confirmDelete(scope.row.id)"
            >
              删除
            </el-button>
          </div>
          <el-button type="text" style="color:#606266 !important;" @click="attendance_duty_show(scope.row.id)" v-if="scope.row.type != 2">排班表</el-button>
          <el-button type="text" style="color:#606266 !important;" @click="corde(scope.row)">积分设置</el-button>
        </template>
      </el-table-column>
    </el-table>

    <center style="margin: 20px;">
      <el-pagination
        background
        layout="total,sizes, prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageLimit"
        :total="totalCount"
        @size-change="handleSizeChange"
        :current-page.sync="currentPage"
        @current-change="changePage"
      ></el-pagination>
    </center>

    <el-dialog class="attendance_group" :title="dialog_title" @close="formReset" :visible.sync="RuleDetailDialogVisible" width="800px" top="50px">
      <div style="padding:0 50px;" v-if="dialog_title != '创建考勤组'">
        <el-alert style="margin-bottom:30px;" title="修改设置会影响现有排班，请谨慎操作！" type="warning"></el-alert>
      </div>

      <div style="padding:0 50px;">
          <el-form ref="formdata" :model="formdata" label-width="100px" :rules="formrule">
            <el-form-item label="考勤组名称" prop="name"><el-input style="width:350px;" maxlength="30" v-model="formdata.name"></el-input></el-form-item>
            <el-form-item label="参与人员" prop="employee_ids">
              <el-card class="box-card" shadow="hover">
                <div class="tag-box-padding">
                  <el-tag v-for="(tag, index) in formdata.employee" :key="index" type="success" @close="employee_delete(tag.id, index)" closable>{{ tag.name }}</el-tag>
                  <el-button size="mini" @click="EmployeeSelector0_show">选择</el-button>
                </div>
              </el-card>
            </el-form-item>

            <el-form-item label="不参与人员" v-if="formdata.employee.length != 0">
              <el-card class="box-card" shadow="hover">
                <div class="tag-box-padding">
                  <el-tag v-for="(tag, index) in formdata.un_employee" :key="index" @close="un_employee_delete(tag.id, index)" type="success" closable>{{ tag.name }}</el-tag>
                  <el-button size="mini" @click="EmployeeSelector1_show">选择</el-button>
                </div>
              </el-card>
            </el-form-item>

            <el-form-item label="考勤类型">
              <el-radio-group v-model="formdata.type" :disabled="profile.manager_type < 2 || isChose">
                <el-radio :label="0">固定班制</el-radio>
                <el-radio :label="1">排班制</el-radio>
                <el-radio :label="2">自由上下班</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="班次">
              <el-tag @close="attendance_setting_delete(tag, index)" v-for="(tag, index) in formdata.attendance_setting_list" :key="index" type="success" closable>
                {{ tag.name }}
              </el-tag>
              <el-button size="mini" @click="class_selector_show">选择班次</el-button>
            </el-form-item>
            <div style="position: relative;top:-10px;left: 100px;font-size: 12px;" class="orange">如您操作删除了部分班次，请注意检查【排班表】并取消相关班次的排班</div>
            <el-form-item label="工作日" v-if="formdata.type == 2">
              <el-checkbox-group v-model="work_date_list">
                <el-checkbox v-for="(item, index) in formdata.work_date" :key="index" :label="index" name="work_date">{{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="排班周期" v-if="formdata.type == 1">
              <el-select v-model="work_date_length" placeholder="2">
                <el-option label="2天" :value="2"></el-option>
                <el-option label="3天" :value="3"></el-option>
                <el-option label="4天" :value="4"></el-option>
                <el-option label="5天" :value="5"></el-option>
                <el-option label="6天" :value="6"></el-option>
                <el-option label="7天" :value="7"></el-option>
                <el-option label="8天" :value="8"></el-option>
                <el-option label="9天" :value="9"></el-option>
                <el-option label="10天" :value="10"></el-option>
                <el-option label="11天" :value="11"></el-option>
                <el-option label="12天" :value="12"></el-option>
                <el-option label="13天" :value="13"></el-option>
                <el-option label="14天" :value="14"></el-option>
                <el-option label="15天" :value="15"></el-option>
                <el-option label="16天" :value="16"></el-option>
                <el-option label="17天" :value="17"></el-option>
                <el-option label="18天" :value="18"></el-option>
                <el-option label="19天" :value="19"></el-option>
                <el-option label="20天" :value="20"></el-option>
                <el-option label="21天" :value="21"></el-option>
                <el-option label="22天" :value="22"></el-option>
                <el-option label="23天" :value="23"></el-option>
                <el-option label="24天" :value="24"></el-option>
                <el-option label="25天" :value="25"></el-option>
                <el-option label="26天" :value="26"></el-option>
                <el-option label="27天" :value="27"></el-option>
                <el-option label="28天" :value="28"></el-option>
                <el-option label="29天" :value="29"></el-option>
                <el-option label="30天" :value="30"></el-option>
                <el-option label="31天" :value="31"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item v-if="formdata.type == 1">
              <el-table border :data="formdata.work_date" style="width: 350px;">
                <el-table-column width="80" prop="name" label="时间"></el-table-column>
                <el-table-column prop="setting_id" label="班次">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.setting_id" placeholder="请选择">
                      <el-option v-for="item in formdata.attendance_setting_list" :key="item.value" :label="item.name" :value="item.value"></el-option>
                      <el-option :key="0" label="休息（不上班）" :value="0"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>

            <el-form-item v-if="formdata.type == 0">
              <el-table border :data="formdata.work_date" style="width: 350px;">
                <el-table-column width="80" prop="name" label="时间"></el-table-column>
                <el-table-column prop="setting_id" label="班次">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.setting_id" placeholder="请选择">
                      <el-option v-for="item in formdata.attendance_setting_list" :key="item.value" :label="item.name" :value="item.value"></el-option>
                      <el-option :key="0" label="休息（不上班）" :value="0"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>

            <el-form-item label="必须打卡日期" v-if="formdata.type == 2">
              <el-card class="box-card" shadow="hover">
                <div class="tag-box-padding">
                  <el-tag color="#fff" v-for="(tag, index) in formdata.date_must" :key="tag" type="success" @change="changeTag" @close="date_must_delete(tag, index)" closable>
                    {{ tag }}
                  </el-tag>
                  <el-button @click="DateMustShow" size="mini">选择日期</el-button>
                </div>
              </el-card>
            </el-form-item>

            <el-form-item label="不用打卡日期" v-if="formdata.type == 2">
              <el-card class="box-card" shadow="hover">
                <div class="tag-box-padding">
                  <el-tag v-for="(tag, index) in formdata.date_not" :key="tag" @close="date_not_delete(tag, index)" type="success" closable>{{ tag }}</el-tag>
                  <el-button size="mini" @click="DateNotShow">选择日期</el-button>
                </div>
              </el-card>
            </el-form-item>

            <el-form-item label="打卡位置" class="is-required">
              <el-card class="box-card" shadow="hover">
                <el-button size="mini" @click="show_map_com">添加位置</el-button>
                <span style="color:#999; padding-left:1rem;">您可以添加多个位置并且设置有效打卡距离</span>
                <div v-for="(l, li) in formdata.location" @click.stop="openMap(l)" :key="li" role="alert" class="el-alert el-alert--success" style="margin-top: 15px;">
                  <div class="el-alert__content">
                    <div class="el-alert__title is-bold">{{l.name2}}</div>
                    <div class="el-alert__description">{{ '有效打卡范围' + l.radius + '米' }}</div>
                    <div class="el-alert__description">{{ l.name }}</div>
                    <i class="el-alert__closebtn el-icon-close" @click.stop="location_del(li)"></i>
                  </div>
                </div>
              </el-card>
              <el-checkbox v-model="is_out_attendance">允许外勤打卡(外勤打卡不加分)</el-checkbox>
            </el-form-item>

            <el-form-item label="加班规则" prop="overtime_rule">
              <el-select v-model="formdata.overtime_rule" placeholder="请选择">
                <el-option v-for="item in overtime_rule_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="RuleDetailDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveFormData" :loading="save_loading">保 存</el-button>
      </span>
    </el-dialog>


    <!-- 地图展示 -->
    <el-dialog :close-on-click-modal="false" class="setMapBaidu" title="添加打卡位置" :visible.sync="MapBoxDialogVisible" width="700px">
      <div v-loading="bdMap_loading">
        <el-input prefix-icon="el-icon-search" placeholder="请输入地址搜索" v-model="search_keyword" class="input-with-select"></el-input>
        <div style="height: 15px;"></div>

        <baidu-map :center="map_point_set" :zoom="16" ref="map_com" style="position: relative; height: 315px;"
        @tilesloaded="tilesloaded" v-if="map_show_s" scroll-wheel-zoom>
          <!-- 缩放组件 -->
          <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
          <!-- 标记点 -->
          <bm-marker :position="point_set" :dragging="true" @dragging="_point_set"></bm-marker>
          <bm-circle :center="point_set" :radius="point_radius" stroke-color="blue" :stroke-opacity="0.5" :stroke-weight="1" :editing="false"></bm-circle>
          <bm-local-search
            v-show="panel_show"
            @infohtmlset="select_point"
            style="position: absolute; top:-15px; width:100%; height: 315px; overflow-y: scroll; background-color: #fff;"
            :keyword="search_keyword"
          ></bm-local-search>
        </baidu-map>

        <baidu-map class="map" :scroll-wheel-zoom="true" :center="map_point_set" :zoom="16" style="position: relative;" @tilesloaded="tilesloaded" v-if="map_show" scroll-wheel-zoom>
          <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
          <bm-marker :position="point_set" :dragging="true" @dragging="_point_set"></bm-marker>
          <bm-circle :center="point_set" :radius="point_radius" stroke-color="blue" :stroke-opacity="0.5" :stroke-weight="1" :editing="false"></bm-circle>
        </baidu-map>

        <div style="margin-top:15px;">
          有效打卡范围：
          <el-select v-model="point_radius">
            <el-option label="100米" :value="100"></el-option>
            <el-option label="200米" :value="200"></el-option>
            <el-option label="300米" :value="300"></el-option>
            <el-option label="400米" :value="400"></el-option>
            <el-option label="500米" :value="500"></el-option>
            <el-option label="600米" :value="600"></el-option>
            <el-option label="700米" :value="700"></el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <div class="flex-box-end">
            <el-button @click="MapBoxDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveLocationInfo">保 存</el-button>
          </div>
        </span>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="查看设置地点" :visible.sync="isShowMap" width="700px">
      <div v-loading="bdMap_loading">
        <div style="margin-bottom: 20px; text-align: center; font-weight: 600;">{{mapData.name2}}</div>
        <baidu-map :center="mapJw" :zoom="16" ref="map_com" style="height: 315px;" @tilesloaded="tilesloaded" scroll-wheel-zoom>
          <!-- 缩放组件 -->
          <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
          <!-- 标记点 -->
          <bm-marker :position="mapJw"></bm-marker>
          <bm-circle :center="mapJw" :radius="mapData.radius" stroke-color="blue" :stroke-opacity="0.5" :stroke-weight="1" :editing="false"></bm-circle>
        </baidu-map>
        <div style="padding-top: 20px;font-weight: 600;">地点：{{mapData.name}}</div>
        <div style="padding: 20px 0;font-weight: 600;" >有效打卡范围：{{mapData.radius}}米</div>
        <span slot="footer" class="dialog-footer">
          <div class="flex-box-end">
            <el-button type="warning" @click="isShowMap = false">关闭</el-button>
          </div>
        </span>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="必须打卡的日期" :visible.sync="DateMustDialogVisible" width="400px">
      <Calendar v-on:choseDay="choseDaydate_must" :markDate="date_must"></Calendar>
      <span slot="footer" class="dialog-footer"><el-button type="primary" @click="DateMustSave">确 定</el-button></span>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="不用打卡的日期" :visible.sync="DateNotDialogVisible" width="400px">
      <Calendar v-on:choseDay="choseDaydate_not" :markDate="date_not"></Calendar>
      <span slot="footer" class="dialog-footer"><el-button type="primary" @click="DateNotSave">确 定</el-button></span>
    </el-dialog>

    <EmployeeSelector
      :title="'选择参与人员'"
      :isChecKedAll="true"
      :selected="selected0"
      :multi="true"
      :visible.sync="EmployeeSelectorDialogVisible0"
      :close_clear_data="false"
      @confirm="EmployeeSelectorSave0"
    ></EmployeeSelector>

    <EmployeeSelector
      :title="'选择不参与人员'"
      :close_clear_data="false"
      :user_employee_list="true"
      :employee_list="selected0.employee"
      :isChecKedAll="true"
      :selected="selected1"
      :visible.sync="EmployeeSelectorDialogVisible1"
      @confirm="EmployeeSelectorSave1"
    ></EmployeeSelector>

    <EmployeeSelector
      :title="'选择考勤管理员'"
      :selected="selected2"
      :close_clear_data="false"
      :visible.sync="EmployeeSelectorDialogVisible2"
      @confirm="EmployeeSelectorSave2"
    ></EmployeeSelector>

    <el-dialog :close-on-click-modal="false" title="选择班次" :visible.sync="class_selectorDialogVisible" width="800px" top="50px">
      <class_selector v-if="class_selectorDialogVisible"  :selected="attendance_setting_ids" :select_list.sync="attendance_setting_list" :select_ids.sync="attendance_setting_ids"></class_selector>
      <span slot="footer" class="dialog-footer"><el-button type="primary" @click="class_selector_save">确 定</el-button></span>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="排班表" :visible.sync="attendance_dutyDialogVisible" width="90%" top="50px">
      <template slot="title">
        <div style="font-size: 18px;">排班表</div>
        <span style="margin-top: 10px;color: #2dac2d;display: inline-block;">注：*新增和修改排班时，仅支持修改未来的排班（今天及以前的修改不会保存），请提前规划并设置好排班*</span>
      </template>
      <attendance_duty ref="attendance_duty_com" @saved="save_success"></attendance_duty>
      <span slot="footer" class="dialog-footer"><el-button type="primary" @click="attendance_duty_save" :loading="attendance_duty_save_loading">保 存</el-button></span>
    </el-dialog>
    <changeCorde @changDialog="changDialog" :group_id="group_id" :showDialog="showDialog" />
  </div>
</template>
<script>
import Vue from 'vue';
import BaiduMap from 'vue-baidu-map';
import Calendar from 'vue-calendar-component';
import class_selector from '@/point/views/attendance/class_selectornew';
import attendance_duty from '@/point/views/attendance/attendance_dutynew';
import changeCorde from '@/point/views/attendance/attendance_dialognew'; // 考勤设置弹框
import EmployeeSelector from '@/components/EmployeeSelector'; // 考勤设置弹框
Vue.use(BaiduMap, { ak: 'QMDvD2Anle2gLOINIBUZ1Lhh' });

export default {
  components: {
    Calendar,
    EmployeeSelector,
    class_selector,
    attendance_duty,
    changeCorde
  },
  watch: {
    isShowMap(val){
      if(!val){
        this.mapData={};
        this.bdMap_loading = false;
        this.mapJw={lng: 116.404, lat: 39.915};
      }
    },
    attendance_setting_list(val, old) {},
    search_keyword: function(n, o) {
      if (n != '') {
        this.panel_show = true;
        this.map_show_s = true;
        this.map_show = false;
      } else {
        this.map_show_s = false;
        this.map_show = true;
      }
    },
    work_date_length: function(n, o) {
      const work_date = [];
      let setting_id = 0;
      for (let i = 0; i < n; i++) {
        if (i < this.formdata.work_date.length) {
          setting_id = this.formdata.work_date[i].setting_id;
        } else {
          setting_id = 0;
        }
        work_date.push({ name: '第' + (i + 1) + '天', setting_id: setting_id });
      }
      this.formdata.work_date = work_date;
    },
    'formdata.type': function(n, o) {
      const work_date = [];
      if (n != 1) {
        this.formdata.work_date = [
          { name: '周一', setting_id: 0 },
          { name: '周二', setting_id: 0 },
          { name: '周三', setting_id: 0 },
          { name: '周四', setting_id: 0 },
          { name: '周五', setting_id: 0 },
          { name: '周六', setting_id: 0 },
          { name: '周日', setting_id: 0 }
        ];
      } else {
        for (let i = 0; i < this.work_date_length; i++) {
          work_date.push({ name: '第' + (i + 1) + '天', setting_id: this.formdata.work_date[i].setting_id });
        }
        this.formdata.work_date = work_date;
      }
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      var validValue = value ? value.replace(/\s/g, '').replace(/&nbsp;/gi, '') : value;
      if (!validValue) {
        return callback(new Error('请填写积分分类名称'));
      } else {
        callback();
      }
    };
    return {
      show_dept_selector: [],
      isChose: false,
      baseurl: this.$serveAd,
      formrule: {
        name: [{ required: true, message: '请输入名称' }],
        employee_ids: [{ required: true, message: '请选择参与人员'}],
        manager_ids: [{ required: true, message: '请选择管理员'}],
        overtime_rule: [{ required: true, message: '请选择加班规则'}]
      },
      tag: false,
      group_id: 0,
      showDialog: false, // 控制考勤设置弹窗
      attendance_duty_save_loading: false,
      class_selectorDialogVisible: false,
      attendance_dutyDialogVisible: false,
      save_loading: false,
      EmployeeSelectorDialogVisible0: false,
      EmployeeSelectorDialogVisible1: false,
      EmployeeSelectorDialogVisible2: false,
      DateMustDialogVisible: false,
      DateNotDialogVisible: false,
      is_out_attendance: true,
      location_name: '',
      location_details: '',
      map_show_s: true,
      map_show: false,
      search_location: '',
      search_keyword: '',
      panel_show: false,
      map_point_set: { lng: 116.404, lat: 39.915 },
      point_set: { lng: 116.404, lat: 39.915 },
      point_radius: 300,

      MapBoxDialogVisible: false,
      dialog_title: '创建考勤组',
      work_date_length: 2,
      work_date_list: [],

      employee_ids: [],
      un_employee_ids: [],
      manager_ids: [],
      employee_list: [],
      un_employee_list: [],
      manager_list: [],
      attendance_setting_list: [], //  班次列表
      attendance_setting_ids: [], // 班次列表id
      date_must_arr: [],
      attendance_setting_list_must: [],
      formdata: {
        name: '',
        employee_ids: [], // 参与人员id
        employee: [],
        manager_ids: [],
        manager: [], // 考勤管理yuan
        un_employee_ids: '',
        un_employee: [], // 不参与人员
        attendance_setting_ids: [],
        attendance_setting_list: [],
        work_date: [
          { name: '周一', setting_id: 0 },
          { name: '周二', setting_id: 0 },
          { name: '周三', setting_id: 0 },
          { name: '周四', setting_id: 0 },
          { name: '周五', setting_id: 0 },
          { name: '周六', setting_id: 0 },
          { name: '周日', setting_id: 0 }
        ],
        date_must: [], // 必须打卡日期
        date_not: [], // 不必须打卡日期
        type: 0,
        location_range: 300, // 打卡半径
        location: [], // 打卡位置
        overtime_rule: 0 // 加班规则
      },
      date_must: [],
      date_not: [],
      multipleSelection: [],
      RuleDetailDialogVisible: false,
      pageLimit: 10,

      profile: this.$store.getters.user_info,
      filter: {
        status: 1,
        keywords: '',
        employee_id: null
      },
      overtime_rule_list: [],
      form_api: '/integral.php/attendance_group/create_attend_group',
      loading: false,

      totalCount: 0,
      currentPage: 1,
      tableData: null,
      groupId: '',
      rules: {
        name: [{ validator: validateName, trigger: 'blur' }]
      },
      selected0: { employee: [], dept: [] },
      selected1: { employee: [], dept: [] },
      selected2: { employee: [], dept: [] },
      bdMap_loading: true,

      // 打开设置好的地点相关
      isShowMap:false,
      mapData:{},
      mapJw:{lng: 116.404, lat: 39.915},

      employee_map: '', //人员列表
    };
  },
  methods: {
    inits(){
      let obj_map = Object.values(this.$getEmployeeMap())
      let arr = obj_map.filter( x => this.$supremeAuthority(null,x.id) != 'creator')//去掉创始人
      this.employee_map = arr;
    },
    employeSearch(val){
      this.currentPage = 1;
      this.loadRuleList();
    },
    // 打开设置好的地图
    openMap(i){
     this.mapJw={ lng: i.lng, lat:i.lat };
     this.mapData=i;
     this.bdMap_loading = true;
     this.$nextTick(()=>{
        this.isShowMap=true;
     })
    },
    tilesloaded() {
      this.bdMap_loading = false;
    },
    location_del(index) {
      this.formdata.location.splice(index, 1);
    },
    // 打开排班表
    attendance_duty_show(id) {
      const self = this;
      this.attendance_dutyDialogVisible = true;
      this.$nextTick(function() {
        self.$refs['attendance_duty_com'].get_group_info(id);
      });
    },
    attendance_duty_save() {
      const self = this;
      self.attendance_duty_save_loading = true;
      self.$refs['attendance_duty_com'].send_schedule();
    },
    save_success() {
      const self = this;
      self.attendance_duty_save_loading = false;
      self.attendance_dutyDialogVisible = false;
    },
    class_selector_save() {
      for (let i in this.formdata.attendance_setting_ids) {
        this.formdata.attendance_setting_ids[i] = Number(this.formdata.attendance_setting_ids[i]);
      }
      for (const l in this.attendance_setting_list) {
        if (this.formdata.attendance_setting_ids.indexOf(this.attendance_setting_list[l].id) < 0) {
          this.formdata.attendance_setting_ids.push(this.attendance_setting_list[l].id);
          this.formdata.attendance_setting_list.push({ name: this.attendance_setting_list[l].name, value: this.attendance_setting_list[l].id });
        }
      }
      this.setMustDateArr();
      this.class_selectorDialogVisible = false;
    },
    class_selector_show() {
      this.class_selectorDialogVisible = true;
    },
    EmployeeSelector0_show() {
      this.EmployeeSelectorDialogVisible0 = true;
    },
    EmployeeSelector1_show() {
      this.EmployeeSelectorDialogVisible1 = true;
    },
    EmployeeSelector2_show() {
      this.EmployeeSelectorDialogVisible2 = true;
    },

    set_manager_ids(data) {
      this.manager_list = data;
    },
    set_un_employee_ids(data) {
      this.un_employee_list = data;
    },
    set_employee_ids(data) {
      this.employee_list = data;
    },
    EmployeeSelectorSave0(data) {
      this.EmployeeSelectorDialogVisible0 = false;
      //this.employee_list = data.employee
      this.employee_list = JSON.parse(JSON.stringify(data.employee));
      let selectedLing = this.selected0.employee;
      let differenceValue = selectedLing.filter(a => !this.employee_list.some(b => b.id == a.id));
      if (this.employee_list != 0) {
        for (let i in this.formdata.un_employee) {
          for (let a in differenceValue) {
            if (this.formdata.un_employee[i].id == differenceValue[a].id) {
              this.formdata.un_employee.splice(i, 1);
            }
          }
        }

        let un_employeeList = [];
        for (let i in this.formdata.un_employee) {
          un_employeeList.push(this.formdata.un_employee[i].id);
        }
        this.formdata.un_employee_ids = un_employeeList;
      } else {
        this.formdata.un_employee = [];
        this.formdata.un_employee_ids = [];
      }
      this.selected1.employee = this.formdata.un_employee;

      this.selected0 = data;
      this.formdata.employee = [];
      this.formdata.employee_ids = [];
      if (this.employee_list.length != 0) {
        for (const i in this.employee_list) {
          this.formdata.employee.push(this.employee_list[i]);
          this.formdata.employee_ids.push(this.employee_list[i].id);
        }
      }
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val;
    },
    EmployeeSelectorSave1(data) {
      this.EmployeeSelectorDialogVisible1 = false;
      this.un_employee_list = JSON.parse(JSON.stringify(data.employee));
      this.selected1 = data;
      this.formdata.un_employee = [];
      this.formdata.un_employee_ids = [];
      if (this.un_employee_list.length != 0) {
        for (const i in this.un_employee_list) {
          this.formdata.un_employee.push(this.un_employee_list[i]);
          this.formdata.un_employee_ids.push(this.un_employee_list[i].id);
        }
      }
    },
    EmployeeSelectorSave2(data) {
      this.EmployeeSelectorDialogVisible2 = false;
      this.manager_list = JSON.parse(JSON.stringify(data.employee));
      this.formdata.manager_ids = this.formdata.manager_ids.map(item => (item = Number(item)));
      this.selected2 = data;
      this.formdata.manager = [];
      this.formdata.manager_ids = [];
      if (this.manager_list.length != 0) {
        for (const i in this.manager_list) {
          this.formdata.manager.push(this.manager_list[i]);
          this.formdata.manager_ids.push(this.manager_list[i].id);
          // }
        }
      }
    },
    choseDaydate_must(data) {
      if (this.formdata.date_not.indexOf(data) >= 0) {
        this.$message.error('当前日期已被选中为“不用打卡日期”');
        return;
      }
      if (this.formdata.date_must.indexOf(data) >= 0) {
        this.$message.error('当前日期已被选中');
        return;
      }
      if (this.date_must.indexOf(data) >= 0) {
        this.date_must.splice(this.date_must.indexOf(data), 1);
      } else {
        this.date_must.push(data);
      }
    },
    choseDaydate_not(data) {
      if (this.formdata.date_must.indexOf(data) >= 0) {
        this.$message.error('当前日期已被选中为“必须打卡日期”');
        return;
      }
      if (this.date_not.indexOf(data) >= 0 || this.formdata.date_not.indexOf(data) >= 0) {
        this.$message.error('当前日期已被选中');
        return;
      }
      if (this.date_not.indexOf(data) >= 0) {
        this.date_not.splice(this.date_not.indexOf(data), 1);
      } else {
        this.date_not.push(data);
      }
    },
    DateNotShow() {
      this.date_not = [];
      this.DateNotDialogVisible = true;
    },
    DateMustShow() {
      this.date_must = [];
      this.DateMustDialogVisible = true;
    },

    DateNotSave() {
      this.DateNotDialogVisible = false;
      for (const i in this.date_not) {
        if (this.formdata.date_not.indexOf(this.date_not[i]) < 0) {
          this.formdata.date_not.push(this.date_not[i]);
        }
      }
    },
    DateMustSave() {
      this.DateMustDialogVisible = false;
      for (const i in this.date_must) {
        if (this.formdata.date_must.indexOf(this.date_must[i]) < 0) {
          this.formdata.date_must.push(this.date_must[i]);
        }
      }
      this.setMustDateArr();
    },
    setMustDateArr() {
      const attendance_setting_list_must = {};
      for (const i in this.formdata.date_must) {
        attendance_setting_list_must[this.formdata.date_must[i]] = [];
        for (const item in this.formdata.attendance_setting_list) {
          attendance_setting_list_must[this.formdata.date_must[i]].push({
            label: this.formdata.date_must[i] + '(' + this.formdata.attendance_setting_list[item].label + ')',
            value: this.formdata.date_must[i] + ':' + this.formdata.attendance_setting_list[item].value
          });
        }
      }
      this.attendance_setting_list_must = attendance_setting_list_must;
    },
    saveLocationInfo() {
      if (this.location_name == '') {
        this.$message.error('搜索地址名称或者拖动地图中的红色标签确定位置');
        return;
      }
      this.formdata.location.push({ lat: this.point_set.lat, lng: this.point_set.lng, name: this.location_name, radius: this.point_radius,name2:this.search_keyword });
      this.MapBoxDialogVisible = false;
    },
    // 拖动标记点
    _point_set(a) {
      const _this = this;
      this.point_set = a.point;
      const geoc = new BMap.Geocoder();
      geoc.getLocation(a.point, function(rs) {
        const addComp = rs.addressComponents;
        _this.location_name = addComp.province + ' ' + addComp.city + ' ' + addComp.district + ' ' + addComp.street + ' ' + addComp.streetNumber;
      });
    },
    // 搜索地点
    select_point(p) {
      const _this = this;
      const geoc = new BMap.Geocoder();
      geoc.getLocation(p.point, function(rs) {
        const addComp = rs.addressComponents;
        _this.location_name = addComp.province + ' ' + addComp.city + ' ' + addComp.district + ' ' + addComp.street + ' ' + addComp.streetNumber;
      });
      this.point_set = p.point;
      this.map_point_set = p.point;
      this.search_keyword=p.title;
      this.panel_show = false;
      setTimeout(function() {
        _this.map_show = true;
        _this.map_show_s = false;
      }, 200);
    },

    show_map_com() {
      const _this = this;
      this.MapBoxDialogVisible = true;
    },
    // 必打卡日期选择班次
    selectDate() {},
    date_must_delete(tag, index) {
      this.formdata.date_must.splice(index, 1);
      this.date_must_arr.splice(index, 1);
    },
    changeTag() {},
    date_not_delete(tag, index) {
      this.formdata.date_not.splice(index, 1);
    },
    employee_delete(id, index) {
      for (let i in this.formdata.un_employee) {
        if (this.formdata.un_employee[i].id == id) {
          this.formdata.un_employee.splice(i, 1);
        }
      }
      let un_employeeList = [];
      for (let i in this.formdata.un_employee) {
        un_employeeList.push(this.formdata.un_employee[i].id);
      }
      this.formdata.un_employee_ids = un_employeeList;
      this.formdata.employee.splice(index, 1);
      this.selected0.employee = this.formdata.employee;
      const employee_ids = [];
      for (const e in this.formdata.employee) {
        employee_ids.push(this.formdata.employee[e].id);
      }
      this.formdata.employee_ids = employee_ids;
    },

    // 不参与人员
    un_employee_delete(id, index) {
      this.formdata.un_employee.splice(index, 1);
      this.selected1.employee = this.formdata.un_employee;
      const employee_ids = [];
      for (const e in this.formdata.un_employee) {
        employee_ids.push(this.formdata.un_employee[e].id);
      }
      this.formdata.un_employee_ids = employee_ids;
    },

    // 考勤管理员
    manager_delete(id, index) {
      this.formdata.manager.splice(index, 1);
      this.selected2.employee = this.formdata.manager;
      const employee_ids = [];
      for (const e in this.formdata.manager) {
        employee_ids.push(this.formdata.manager[e].id);
      }
      this.formdata.manager_ids = employee_ids;
    },
    attendance_setting_delete(e, index) {
      this.formdata.attendance_setting_list.splice(index, 1);
      const attendance_setting_ids = [];
      for (const i in this.formdata.attendance_setting_list) {
        attendance_setting_ids.push(this.formdata.attendance_setting_list[i].value);
      }
      this.formdata.attendance_setting_ids = attendance_setting_ids;
    },
    confirmMultipleDelete() {
      if (this.multipleSelection.length < 1) {
        return false;
      }
      this.$confirm('确定要删除选中的考勤组吗?', '批量删除考勤组', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const targetArr = [];
          for (const index in this.multipleSelection) {
            targetArr.push(this.multipleSelection[index].id);
          }
          const targetIds = targetArr.join(',');
          this.deleteRule(targetIds, true);
        })
        .catch(() => {});
    },
    handleSizeChange(val) {
      this.pageLimit = val;
      this.onFilterChanged();
    },
    formReset() {
      const _this = this;
    },
    onFilterChanged: function() {
      this.currentPage = 1;
      this.loadRuleList();
    },
    // 获取规则列表
    loadRuleList: function() {
      var self = this;
      self.loading = true;
      var params = {
        page: this.currentPage,
        page_size: this.pageLimit,
        keyword: self.filter.keywords,
        employee_id: self.filter.employee_id,
      };
      this.$axiosKq('get','/ad/group', params
        )
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false;
            var jsonData = response.data;
            try {
              self.totalCount = jsonData.data.total;
              self.tableData = jsonData.data.list;
            } catch (err) {}
          }
        });
    },
    changePage: function(current) {
      if (isNaN(current) || current < 1) {
        return false;
      }
      this.loadRuleList();
    },
    // 创建修改考勤组
    saveFormData: function() {
      // this.save_loading = true
      var self = this;
      const send_data = JSON.parse(JSON.stringify(this.formdata));
      const work_date = [];
      for (const i in send_data.work_date) {
        work_date.push(send_data.work_date[i].setting_id);
      }
      // send_data.date_must = self.date_must_arr
      if (send_data.type == 2) {
        // 自由上下班
        send_data.work_date = self.work_date_list;
      } else {
        send_data.work_date = work_date;
      }
      if (self.is_out_attendance) {
        send_data['is_out_attendance'] = 1;
      } else {
        send_data['is_out_attendance'] = 0;
      }
      let newarray = [];
      for (let i = 0; i < send_data.date_must.length; i++) {
        // newarray.push(send_data.date_must[i]+ ':' + self.date_must_arr[i]);
        newarray.push(send_data.date_must[i]);
      }
      var params = {
        name: '',
        schedule_ids: '', // 班次ID集合，如 2,24,1
        employee_ids: '', // 考情id
        manager_ids: '', // 考勤组管理员ID
        un_employee_ids: '', // 不参与人员
        work_date: '', // 	排班周期每天的班次ID，逗号隔开，如 2,24,1 当type为2时，使用1-7来说明周一至周日是否上班
        date_must: '', // 必打卡日期
        date_not: '', // 不比打卡日期
        type: 0, // 考勤组类型，0固定班制，1排班制，2自由上下班
        location_list: [], //考勤打卡的地点和范围，如[{name: “东莞市莞太路34号”, lng: 23.836343, lat: 113.3734643, radius: 300}]
        is_out_attendance: 0, // 是否允许外勤打卡，1是，0否
        overtime_rule: '' // 加班规则ID
      };
      params.schedule_ids = send_data.attendance_setting_ids.join(',');
      params.name = send_data.name;
      params.employee_ids = send_data.employee_ids.join(',');
      params.manager_ids = send_data.manager_ids.join(',');
      params.un_employee_ids = send_data.un_employee_ids.join(',');
      params.work_date = send_data.work_date.join(',');
      params.date_must = newarray.join(',');
      params.date_not = send_data.date_not.join(',');
      params.type = send_data.type;
      params.location_list = send_data.location;
      params.is_out_attendance = send_data.is_out_attendance;
      params.overtime_rule = send_data.overtime_rule;

      if (self.groupId > 0) {
        params.id = self.groupId;
      }
      if (self.is_out_attendance) {
        send_data['is_out_attendance'] = 1;
      } else {
        send_data['is_out_attendance'] = 0;
      }
      if (params.name == '') {
        this.$message({
          message: '请输入考勤组名称',
          type: 'error'
        });
        return false;
      } else if (params.employee_ids == '') {
        this.$message({
          message: '请选择参与人员',
          type: 'error'
        });
        return false;
      }
       else if (params.overtime_rule == '') {
        this.$message({
          message: '请选择加班规则',
          type: 'error'
        });
        return false;
      }
      this.$axiosKq('post',this.form_api,params)
        .then(function(response) {
          self.save_loading = false;
          if (response.status == 200) {
            if (response.data.code == 1) {
              self.RuleDetailDialogVisible = false;
              self.onFilterChanged();
              self.$message.success(response.data.msg);
            } else {
              self.$message.error(response.data.msg);
            }
          }
        })
    },

    confirmDelete: function(ruleId) {
      this.$confirm('确定要删除此考勤组吗？', '删除考勤组', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteRule(ruleId);
        })
        .catch(() => {});
    },
    // 获取默认规则
    get_overtime_list() {
      const self = this;
      var params = { page: 1, page_size: 1000, interval: 1000 };
      this.$axiosKq('get','/ad/over_time_rule',params).then(res => {
        if (res.status == 200) {
          self.overtime_rule_list = res.data.data.list;
        }
      });
    },
    // 删除考情组
    deleteRule: function(ruleId) {
      if (!ruleId) {
        return false;
      }
      const params = { id: ruleId };
      var self = this;
      this.$axiosKq('get','/ad/group/delete',params)
        .then(function(response) {
          if (response.status == 200 && response.data.code == 1) {
            self.$message.success(response.data.msg);
            self.loadRuleList();
          } else {
            // self.$message.error('网络错误');
          }
        })
        .catch(function(error) {});
    },
    corde: function(data) {
      this.group_id = data.id;
      this.showDialog = true;
    },
    changDialog: function() {
      this.showDialog = false;
      this.loadRuleList();
    },

    // 修改创建打开窗口  获取详情
    toDetailPage: function(id, event) {
      const self = this;
      self.date_must_arr = [];
      self.formdata = {
        name: '',
        employee_ids: [],
        employee: [],
        manager_ids: [],
        manager: [],
        un_employee_ids: [],
        un_employee: [],
        attendance_setting_ids: [],
        attendance_setting_list: [],
        work_date: [
          { name: '周一', setting_id: 0 },
          { name: '周二', setting_id: 0 },
          { name: '周三', setting_id: 0 },
          { name: '周四', setting_id: 0 },
          { name: '周五', setting_id: 0 },
          { name: '周六', setting_id: 0 },
          { name: '周日', setting_id: 0 }
        ],
        date_must: [],
        date_not: [],
        type: 0,
        location_range: 300,
        location: [],
        overtime_rule: ''
      };
      let newdate = [
        { name: '周一', setting_id: 0 },
        { name: '周二', setting_id: 0 },
        { name: '周三', setting_id: 0 },
        { name: '周四', setting_id: 0 },
        { name: '周五', setting_id: 0 },
        { name: '周六', setting_id: 0 },
        { name: '周日', setting_id: 0 }
      ];
      if (id > 0) {
        self.groupId = id;
        self.isChose = true;
        this.form_api ='/ad/group/update'; // 确认修改
        this.tag = true;
        this.dialog_title = '修改考勤组';
        // 获取一条记录，用于复原修改界面
        this.$axiosKq('get','/ad/group/info',{ id: id }).then(res => {
          if (res.status == 200) {
            self.is_out_attendance = res.data.data.is_out_attendance == 1;
            self.formdata.name = res.data.data.name;
            self.formdata.date_must = res.data.data.date_must.split(',');
            self.formdata.employee_ids = res.data.data.employee_ids.split(',');
            self.formdata.employee = res.data.data.employees;
            self.selected0.employee = res.data.data.employees;

            self.formdata.manager = res.data.data.managers;
            self.selected2.employee = res.data.data.managers;

            self.formdata.un_employee = res.data.data.un_employees;
            self.selected1.employee = res.data.data.un_employees;
            self.formdata.manager_ids = res.data.data.manager_ids.split(',');

            let work_date_list = res.data.data.work_date.split(','); // 返回选中班次id
            let schedules = res.data.data.schedules;

            self.formdata.un_employee_ids = res.data.data.un_employee_ids.split(',');

            if (res.data.data.type == 0) {
              for (const i in work_date_list) {
                self.formdata.work_date[i].setting_id = work_date_list[i] * 1;
              }
            }
            // 排班制
            if (res.data.data.type == 1) {
              self.formdata.work_date = [];
              self.work_date_length = res.data.data.work_date.split(',').length; // 排班周期
              for (const i in work_date_list) {
                self.formdata.work_date.push({ name: '第' + (i * 1 + 1) + '天', setting_id: work_date_list[i] * 1 });
              }
            }
            // 固定轮休
            if (res.data.data.type == 2) {
              self.work_date_list = work_date_list.map(function(item) {
                return 1 * item;
              });
            }

            self.attendance_setting_list = res.data.data.schedules;
            let newSetting = [];
            for (let i = 0; i < res.data.data.schedules.length; i++) {
              self.attendance_setting_list[i].value = res.data.data.schedules[i].id;
              newSetting.push({});
              newSetting[i].value = res.data.data.schedules[i].id;
              newSetting[i].name = res.data.data.schedules[i].name;
            }
            self.formdata.attendance_setting_list = newSetting;
            self.attendance_setting_ids = res.data.data.schedule_ids.split(',');
            for (let i = 0; i < res.data.data.schedules.length; i++) {
            }

            self.formdata.attendance_setting_ids = res.data.data.schedule_ids.split(',');
            self.formdata.overtime_rule = res.data.data.overtime_rule; // 默认规则

            let newarray = [];
            let newData = [];
            let mustaRRAY = res.data.data.date_must_array;
            for (let i = 0; i < mustaRRAY.length; i++) {
              newarray.push(Number(mustaRRAY[i].schedule_id));
              newData.push(mustaRRAY[i].date);
            }
            self.date_must_arr = newarray;
            if(res.data.data.date_not){
                self.formdata.date_not = res.data.data.date_not.split(',');
            }
            self.formdata.location = res.data.data.location_list;
            self.formdata.type = res.data.data.type; // 考情类型
            self.formdata.id = res.data.data.id;
            self.RuleDetailDialogVisible = true;

            self.setMustDateArr();
          } else {
            // self.$message.error('网络错误');
          }
        });
      } else {
        this.isChose = false;
        this.tag = false;
        this.RuleDetailDialogVisible = true;
        //清空选人组件
        (this.selected0 = { employee: [], dept: [] }),
          (this.selected1 = { employee: [], dept: [] }),
          (this.selected2 = { employee: [], dept: [] }),
          (this.form_api ='/ad/group/add');
        this.dialog_title = '创建考勤组';
      }
    }
  },
  created() {
    this.inits()
    this.get_overtime_list();
    this.loadRuleList();
  }
};
</script>
<style scoped>
.el-alert--success:hover{
  background-color: #F5F5F5;
  cursor: pointer;
}
.el-alert__content{
  line-height: 24px;
}
.el-alert__closebtn{
  width: 20px;
  height: 20px;
  font-size: 16px;
  text-align: center;
  line-height: 20px;
}
.el-alert__closebtn:hover{
  background-color: #E65D6E;
  border-radius: 50%;
  color: #fff;
}
/deep/ .date_tag .el-tag + .el-tag {
  margin: 5px;
}

/deep/ .attendance_group .el-card__body {
  padding: 15px;
}
/deep/ .attendance_group .el-tag + .el-tag {
  margin-left: 10px;
}
/deep/ .attendance_group .el-tag + .el-button {
  margin-left: 10px;
}

.setMapBaidu .map {
  width: 100%;
  height: 300px;
}
.diy-input-on-border input {
  background-color: transparent;
  border: none;
}
/deep/ .wh_container .wh_content_all {
  background: #5b8bf7;
}
</style>
