<template>
  <div>
    <!--   百度地图模块   -->
    <el-dialog width="70%" height="700px" title="地图" :visible.sync="innerVisible" append-to-body>
      <baidu-map
        v-if="handReset"
        ref="map"
        :style="mapStyle"
        :center="center"
        :zoom="9"
        :scroll-wheel-zoom="true"
        :dragging="true"
        @click="clickMap"
      >
        <bm-boundary
          name="宁夏回族自治区"
          :strokeWeight="1"
          strokeColor="blue"
          fillColor="#87a1bc"
          :fillOpacity="fillOpacityValue"
        ></bm-boundary>
        <bm-view style="width: 100%; height: 100%" />
        <bm-marker
          :position="{ lng: center.lng, lat: center.lat }"
          :dragging="true"
          animation="BMAP_ANIMATION_BOUNCE"
        />
        <bm-control :offset="{ width: '10px', height: '10px' }">
          <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 100 }">
            <el-input v-model="keyword" type="text" placeholder="请输入地名关键字" v-no-whitespace clearable>
              <i slot="prefix" class="el-input__icon el-icon-search" />
            </el-input>
          </bm-auto-complete>
        </bm-control>
        <bm-control anchor="BMAP_ANCHOR_BOTTOM_RIGHT">
          <el-button icon="el-icon-check" circle @click="addressDirectory"></el-button>
        </bm-control>
        <bm-local-search
          :keyword="keyword"
          :auto-viewport="true"
          :panel="mapDetails"
          location=""
          zoom="19"
          :selectFirstResult="true"
        />
      </baidu-map>
    </el-dialog>
    <el-form ref="elForm" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="打卡时间" prop="clockInTime">
        <el-checkbox-group v-model="form.clockInTime" @change="changeCheckbox">
          <el-checkbox v-for="item in checkList" :key="item.value" :label="item.value" :name="item.label">
            {{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="上班打卡时间" prop="upperWorkTime">
        <el-time-picker
          v-model="form.upperWorkTime"
          value-format="HH:mm"
          format="HH:mm"
          placeholder="请选择上班打开时间"
          style="width: 230px"
        />
      </el-form-item>
      <el-form-item label="下班打卡时间" prop="belowWorkTime">
        <el-time-picker
          v-model="form.belowWorkTime"
          value-format="HH:mm"
          format="HH:mm"
          placeholder="请选择下班打卡时间"
          style="width: 230px"
        />
        <div style="margin-top: 10px; font-size: 12px; color: #b4b4b4">
          <span style="color: red">注：</span>
          迟到、早退、缺卡规则：上班后半小时以内打卡为迟到；超过半小时为旷工；下班前30分钟打卡为早退；未打卡为缺卡
        </div>
      </el-form-item>
      <div v-for="(item, index) in form.addressList" :key="index">
        <el-form-item :label="'打卡点' + (index + 1)" prop="clockName">
          <el-input
            v-model="item.clockName"
            placeholder="请输入" v-no-whitespace
            maxlength="100"
            show-word-limit
            style="width: 230px; margin-right: 20px"
          />
          <el-switch v-model="item.isEnablePunchCard2"></el-switch>
        </el-form-item>
        <el-form-item label="经度" prop="lon">
          <el-input
            v-model="item.lon" v-no-whitespace
            placeholder="请输入经度"
            @focus="toggleInnerDialog(index)"
            style="width: 230px"
          />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input
            v-model="item.lat" v-no-whitespace
            placeholder="请输入纬度"
            @focus="toggleInnerDialog(index)"
            style="width: 230px; margin-right: 20px"
          />
          <el-button
            v-if="index == form.addressList.length - 1 && index < 2"
            type="primary"
            icon="el-icon-plus"
            plain
            circle
            size="mini"
            @click="addAddress"
          ></el-button>
          <el-button
            v-if="index > 0"
            type="danger"
            icon="el-icon-minus"
            plain
            circle
            size="mini"
            @click="remAddress(index)"
          ></el-button>
        </el-form-item>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer" style="display: flex; justify-content: flex-end">
      <el-button size="small" @click="cancel">取 消</el-button>
      <el-button type="primary" size="small" @click="submitForm" v-preventReClick="5000">确 定</el-button>
    </span>
  </div>
</template>

<script>
import { attendanceConfigurationForm, attendanceConfigurationSave } from '@/api/checkInAdmin'

export default {
  name: 'Post',
  dicts: ['sys_normal_disable'],
  props: {
    items: {
      type: Object,
      open: 'true',
      default: () => {
        return {}
      },
    },
    // 在子组件中使用 props 选项去接收来自父组件传递过来的数据
    dialogVisible: Boolean,
    mapHeight: {
      type: Number,
      default: 700,
    },
    width: {
      type: [Number, String],
      default: '85%',
    },
    height: {
      type: [Number, String],
      default: '80%',
    },
  },
  data() {
    return {
      fillOpacityValue: 0.2,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: '',
      // 地图是否显示弹出层
      innerVisible: false,
      currentIndex: 0,
      // 表单参数
      form: {
        proId: '', // 工程id
        clockInTime: [], // 打卡时间
        upperWorkTime: '', // 上班打卡时间
        belowWorkTime: '', // 下班打卡时间
        addressList: [
          {
            clockName: undefined,
            lon: undefined,
            lat: undefined,
            isEnablePunchCard: '1',
            isEnablePunchCard2: true,
          },
        ],
      },
      checkList: [
        { label: '周一', value: 'monday' },
        { label: '周二', value: 'tuesday' },
        { label: '周三', value: 'wednesday' },
        { label: '周四', value: 'thursday' },
        { label: '周五', value: 'friday' },
        { label: '周六', value: 'saturday' },
        { label: '周日', value: 'sunday' },
      ],
      // 表单校验
      rules: {
        clockInTime: [{ required: true, message: '请选择打卡时间', trigger: 'change' }],
        upperWorkTime: [{ required: true, message: '请选择上班打卡时间', trigger: 'change' }],
        belowWorkTime: [{ required: true, message: '请选择下班打卡时间', trigger: 'change' }],
      },
      //top
      top: 50,
      // 地图参数
      keyword: '', // 地区搜索的信息
      handReset: true,
      mapDetails: false,
      center: { lng: 106.07145, lat: 37.427088 },
      mapStyle: {
        width: '100%',
        height: this.mapHeight + 'px',
      },
      lat: '',
      lon: '',
    }
  },
  watch: {
    items: function (val) {
      console.log('监控当前的地图点位', val)
      this.form = val
    },
    // 更新地图点
    center: function (currentValue) {
      console.log('监控当前的地图点位', currentValue)
      // this.BMap.reload()
      this.handReset = false
      this.$nextTick(() => {
        this.handReset = true
      })
    },
  },
  created() {
    console.log(this.items)
  },
  methods: {
    async handleEdit(row) {
      try {
        this.form.proId = row.proId
        this.form.clockInTime = [
          // 默认周一到周五
          'monday',
          'tuesday',
          'wednesday',
          'thursday',
          'friday',
        ]
        this.form.upperWorkTime = ''
        this.form.belowWorkTime = ''
        this.form.addressList = [
          {
            clockName: undefined,
            lon: undefined,
            lat: undefined,
            isEnablePunchCard: '1',
            isEnablePunchCard2: true,
          },
        ]
        this.$nextTick(() => {
          this.$refs['elForm'].clearValidate()
        })

        const params = { proId: row.proId }
        const res = await attendanceConfigurationForm(params)
        console.log('🚀 ~ 编辑回显 ~ res:', res)
        if (!res.data) return
        if (res.data.monday == '1') {
          this.form.clockInTime.push('monday')
        }
        if (res.data.tuesday == '1') {
          this.form.clockInTime.push('tuesday')
        }
        if (res.data.wednesday == '1') {
          this.form.clockInTime.push('wednesday')
        }
        if (res.data.thursday == '1') {
          this.form.clockInTime.push('thursday')
        }
        if (res.data.friday == '1') {
          this.form.clockInTime.push('friday')
        }
        if (res.data.saturday == '1') {
          this.form.clockInTime.push('saturday')
        }
        if (res.data.sunday == '1') {
          this.form.clockInTime.push('sunday')
        }
        this.form.upperWorkTime = res.data.upperWorkTime
        this.form.belowWorkTime = res.data.belowWorkTime
        this.form.addressList = res.data.addressList
        this.form.addressList.forEach(item => {
          item.isEnablePunchCard2 = this.$set(item, 'isEnablePunchCard2', item.isEnablePunchCard == '1')
        })
      } catch (error) {
        console.log('🚀 ~ 编辑 ~ error', error)
      }
    },
    changeCheckbox(val) {
      console.log('changeCheckbox', val)
    },
    /** 地图搜索信息显示隐藏 */
    addressDirectory() {
      this.mapDetails = !this.mapDetails
    },
    /** 地图显示隐藏 */
    toggleInnerDialog(index) {
      console.log('toggleInnerDialog', index)
      this.currentIndex = index
      this.innerVisible = true
    },
    /** 点击地图 */
    clickMap(e) {
      this.center.lng = e.point.lng
      this.center.lat = e.point.lat
      this.lat = e.point.lat
      this.lon = e.point.lng
      this.form.addressList[this.currentIndex].lat = e.point.lat
      this.form.addressList[this.currentIndex].lon = e.point.lng
      setTimeout(() => {
        this.innerVisible = false
      }, 100)
    },
    addAddress() {
      this.form.addressList.push({
        clockName: undefined,
        lon: undefined,
        lat: undefined,
        isEnablePunchCard: '1',
        isEnablePunchCard2: true,
      })
    },
    remAddress(index) {
      this.form.addressList.splice(index, 1)
    },

    // 取消按钮
    cancel() {
      this.$emit('closeMain')
      this.reset()
    },
    // 表单重置
    reset() {
      this.resetForm('elForm')
      this.form.addressList = [
        {
          clockName: undefined,
          lon: undefined,
          lat: undefined,
          isEnablePunchCard: '1',
          isEnablePunchCard2: true,
        },
      ]
    },
    convertToMinutes(time) {
      const [hours, minutes] = time.split(':').map(Number)
      return hours * 60 + minutes
    },
    /** 提交按钮 */
    submitForm() {
      try {
        console.log('this.form:', this.form)
        this.$refs['elForm'].validate(async valid => {
          if (valid) {
            if (this.convertToMinutes(this.form.upperWorkTime) >= this.convertToMinutes(this.form.belowWorkTime)) {
              this.$message.error('上班时间需要早于下班时间')
              return
            }
            let monday = '0'
            let tuesday = '0'
            let wednesday = '0'
            let thursday = '0'
            let friday = '0'
            let saturday = '0'
            let sunday = '0'
            // 遍历 this.form.clockInTime 当中的值,包含对应的值 如monday tuesday 则对应的值为1
            this.form.clockInTime.forEach(item => {
              if (item == 'monday') {
                monday = '1'
              } else if (item == 'tuesday') {
                tuesday = '1'
              } else if (item == 'wednesday') {
                wednesday = '1'
              } else if (item == 'thursday') {
                thursday = '1'
              } else if (item == 'friday') {
                friday = '1'
              } else if (item == 'saturday') {
                saturday = '1'
              } else if (item == 'sunday') {
                sunday = '1'
              }
            })
            let isPass = true
            this.form.addressList.forEach(item => {
              if (!isPass) return
              if (!item.clockName || !item.lon || !item.lat) {
                this.$message.error('请填写完整的打卡点信息')
                return (isPass = false)
              }
              item.isEnablePunchCard = item.isEnablePunchCard2 ? '1' : '0'
            })

            if (!this.form.addressList.some(item => item.isEnablePunchCard2)) {
              this.$message.error('请至少启用一个打卡点')
              return (isPass = false)
            }
            if (!isPass) return

            const params = {
              proId: this.form.proId,
              monday,
              tuesday,
              wednesday,
              thursday,
              friday,
              saturday,
              sunday,
              upperWorkTime: this.form.upperWorkTime,
              belowWorkTime: this.form.belowWorkTime,
              addressList: this.form.addressList,
            }
            console.log('params:', params)
            const res = await attendanceConfigurationSave(params)
            console.log('🚀 ~ 保存编辑 ~ res:', res)
            this.$emit('closeMain')
          }
        })
      } catch (error) {
        console.log('error:', error)
      }
    },
  },
}
</script>
