<template>
  <div class="main">
    <div class="blockName">{{ disable == '1' ? '详情' : '新增' }}巡更路线（ <span class="show-required-icon-star"></span>为必填项）</div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="formContent"
    >
      <div class="formContent-item">
        <el-form-item
          label="所属社区"
          prop="communityId"
        >
          <el-select
            class="width100"
            v-model="ruleForm.communityId"
            placeholder="所属社区"
            clearable
            :disabled="disable == '1' ? true : false"
          >
            <el-option
              v-for="(item, index) in $parent.communityArr"
              :key="index"
              :label="item.communityName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="巡更路线名称"
          prop="routeName"
        >
          <el-input
            v-model="ruleForm.routeName"
            :disabled="disable == '1' ? true : false"
            placeholder="请输入巡更路线名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="巡更点"
          prop="routePointRelationDtos"
        >
          <el-transfer
            v-model="ruleForm.routePointRelationDtos"
            ref="transferTude"
            filterable
            style="margin-bottom: 20px"
            :props="{
                            key: 'id',
                            label: 'pointName',
                            lan: 'latitude',
                            lng: 'longitude',
                            
                        }"
            :titles="['待选列表', '已选列表']"
            @change="handleChange"
            target-order="push"
            :data="patrolArr"
          >
            <div
              slot-scope="{ option }"
              class="transferTudeClass"
            >
              <span>{{ option.pointName }}</span>
              <div>
                <span
                  class="zoniot_font zoniot-icon-shang"
                  @click="optionUp(0, option)"
                ></span>
                <span
                  class="zoniot_font zoniot-icon-xia"
                  @click="optionUp(1, option)"
                ></span>
              </div>
            </div>
          </el-transfer>
          <map-value :point="targetData"></map-value>
        </el-form-item>
      </div>
      <div class="formContent-item">
        <el-form-item
          label="巡更日期"
          prop="startDate"
        >
          <el-date-picker
            class="width100"
            v-model="effectiveDate"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="选择开始日期"
            end-placeholder="选择结束日期"
            @change="effectiveDateToggle"
            :editable="false"
            :disabled="disable == '1' ? true : false"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="巡更时间"
          prop="timePeriod"
        >
          <div
            class="timeList"
            v-for="(item, index) in timePeriod"
            :key="index"
          >
            <el-time-select
              class="width50"
              placeholder="开始时间"
              v-model="item.startTime"
              :picker-options="{
                                start: '00:00',
                                step: '00:15',
                                end: '23:30'
                            }"
              @change="timeChange(item, 'startTime')"
              :disabled="disable == '1' ? true : false"
            ></el-time-select>
            <span>至</span>
            <el-time-select
              placeholder="结束时间"
              v-model="item.endTime"
              class="width50"
              :picker-options="{
                                start: '00:00',
                                step: '00:15',
                                end: '23:30',
                                minTime: item.startTime
                            }"
              @change="timeChange(item, 'endTime')"
              :disabled="disable == '1' ? true : false"
            ></el-time-select>
            <div
              class="sunm"
              @click="addTime(index, 1)"
              v-show="disable == '1' ? false : true"
            >
              <i class="zoniot_font zoniot-icon-tianjia1"></i>
            </div>
            <div
              class="sunm"
              @click="addTime(index, -1)"
              v-show="disable == '1' ? false : true"
              v-if="timePeriod.length > 1 && index != 0"
            >
              <i class="zoniot_font zoniot-icon-shanjian"></i>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label="巡更周期"
          prop="periodValue"
        >
          <el-radio-group
            v-model="ruleForm.periodType"
            :disabled="disable == '1' ? true : false"
          >
            <el-radio :label="1">每周重复</el-radio>
            <el-radio :label="2">间隔天数重复</el-radio>
          </el-radio-group>

          <el-checkbox-group
            v-if="ruleForm.periodType == 1"
            v-model="periodValue"
            :disabled="disable == '1' ? true : false"
          >
            <el-checkbox :label="1">周一</el-checkbox>
            <el-checkbox :label="2">周二</el-checkbox>
            <el-checkbox :label="3">周三</el-checkbox>
            <el-checkbox :label="4">周四</el-checkbox>
            <el-checkbox :label="5">周五</el-checkbox>
            <el-checkbox :label="6">周六</el-checkbox>
            <el-checkbox :label="7">周日</el-checkbox>
          </el-checkbox-group>
          <div
            v-else
            class="periodValueInput"
          >
            每隔
            <el-input-number
              v-model="ruleForm.periodValue"
              controls-position="right"
              :min="0"
              :max="30"
              :disabled="disable == '1' ? true : false"
            ></el-input-number>天进行(输入0-30的数字，0代表每天都要进行任务)
          </div>
        </el-form-item>
        <el-form-item label="定位距离(m)">
          <el-input
            v-model="ruleForm.positioningDistance"
            :disabled="disable == '1' ? true : false"
            placeholder="巡更定位距离，可输入1-100米，不输入则不检查定位距离"
          ></el-input>
        </el-form-item>
        <el-form-item label="拍照/视频要求">
          <el-select
            class="width100"
            v-model="ruleForm.cameraSettings"
            placeholder="请选择拍照/视频要求"
            clearable
            :disabled="disable == '1' ? true : false"
          >
            <el-option
              label="是"
              :value="1"
            ></el-option>
            <el-option
              label="否"
              :value="0"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="按巡更点顺序签到"
          label-width="130"
        >
          <el-radio-group
            v-model="ruleForm.signFlag"
            :disabled="disable == '1' ? true : false"
          >
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input
            type="textarea"
            placeholder="请输入备注信息"
            resize="none"
            :rows="4"
            v-model="ruleForm.remark"
            maxlength="300"
            show-word-limit
            :disabled="disable == '1' ? true : false"
          ></el-input>
        </el-form-item>
      </div>
    </el-form>
    <div
      style="text-align: right"
      v-if="disable == '1' ? false : true"
    >
      <el-button @click="close">取消</el-button>
      <el-button
        type="primary"
        @click="addEdit"
      >保存</el-button>
    </div>
    <div
      style="text-align: right"
      v-if="disable == '1' ? true : false"
    >
      <el-button
        @click="close"
        style="width: 120px;"
      >返回</el-button>
    </div>

  </div>
</template>
<script>
import mapValue from './mapValue.vue';
export default {
  props: ['patrolDetail', 'disable'],
  components: { mapValue },
  data () {
    return {
      disables: false,
      ruleForm: {
        communityId: '',
        routeName: '',
        routePointRelationDtos: [],
        startDate: '',
        endDate: '',
        timePeriod: '',
        periodType: 1,
        periodValue: '',
        positioningDistance: '',
        cameraSettings: '',
        signFlag: 1,
        remark: ''
      },
      periodValue: [],
      timePeriod: [
        {
          startTime: '',
          endTime: ''
        }
      ],
      rules: {
        communityId: [this.$valid.inputRequired('社区名称')],
        routeName: [this.$valid.inputRequired('巡更路线名称')],
        routePointRelationDtos: [this.$valid.selectRequired('巡更点')],
        startDate: [this.$valid.selectRequired('巡更日期')],
        timePeriod: [this.$valid.selectRequired('巡更时间')],
        periodValue: [this.$valid.selectRequired('巡更周期')]
      },
      effectiveDate: [],
      patrolArr: [],
      targetData: []
    };
  },
  watch: {
    'ruleForm.communityId' (e) {
      this.getPoint(e);
    },
    periodValue (e) {
      this.ruleForm.periodValue = e.join();
    }
  },
  methods: {

    disabledDate () {
      debugger
      alert(1)
    },


    //保存
    addEdit () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let url = '/czc-community/patrolRoute/add';
          this.ruleForm;
          let dotArr = (arr) => {
            let dotObj = [];
            arr.map((item, index) => {
              dotObj.push({
                pointId: item,
                order: index
              });
            });
            return dotObj;
          };

          let params = {
            communityId: this.ruleForm.communityId,
            routeName: this.ruleForm.routeName,
            routePointRelationDtos: dotArr(this.ruleForm.routePointRelationDtos),
            startDate: this.ruleForm.startDate,
            endDate: this.ruleForm.endDate,
            timePeriod: this.ruleForm.timePeriod,
            periodType: this.ruleForm.periodType,
            periodValue: this.ruleForm.periodValue,
            positioningDistance: this.ruleForm.positioningDistance,
            cameraSettings: this.ruleForm.cameraSettings,
            signFlag: this.ruleForm.signFlag,
            remark: this.ruleForm.remark
          };
          this.$http
            .post(url, params)
            .then(({ status, msg }) => {
              if (status == 0) {
                this.$message.success(msg);
                this.close();
              } else {
                this.$message.error(msg);
              }
            })
            .catch(() => { });
        }
      });
    },
    effectiveDateToggle (va) {
      let arr = va;
      if (!arr) {
        arr = ['', ''];
      }
      this.ruleForm.startDate = arr[0];
      this.ruleForm.endDate = arr[1];
    },
    close () {
      this.$emit('initPage');
    },
    getPoint (id) {
      if (JSON.stringify(this.patrolDetail) == "{}") {
        this.ruleForm.routePointRelationDtos = [];
        this.targetData = [];
        this.$http.get('/czc-community/patrol/point/getPointList', { id, id }).then(({ data, status, msg }) => {
          this.patrolArr = data;
        });
      } else {
        this.$http.get('/czc-community/patrol/point/getPointList', { id, id }).then(({ data, status, msg }) => {

          this.patrolArr = data;
          for (let i = 0; i < this.patrolArr.length; i++) {

            this.patrolArr[i]['disabled'] = true;
          }
          console.log(this.patrolArr)
          this.handleChange();
        });
      }

    },
    handleChange () {
      this.$nextTick(() => {
        this.targetData = this.$refs.transferTude.targetData;
      });
    },
    addTime (inx, sun) {
      if (sun > 0) {
        this.timePeriod.push({ startTime: '', endTime: '' });
      } else {
        this.timePeriod.splice(inx, 1);
      }
    },
    timeChange (itm, str) {
      if (!!itm['endTime'] && !!itm['startTime']) {
        let TimeArr = [];
        this.timePeriod.map((item, index) => {
          TimeArr.push(`${item.startTime}-${item.endTime}`);
        });
        this.ruleForm.timePeriod = TimeArr.join();
      }
    },
    optionUp (nub, item) {
      if (this.disable != '1') {
        let thisArr = this.ruleForm.routePointRelationDtos;
        let okArr = this.$refs.transferTude.targetData;
        let newArr = [];
        let inx = null;
        thisArr.map((list, index) => {
          if (list == item.id) {
            inx = index;
          }
          return inx;
        });
        if (inx !== null && thisArr.length > 1) {
          //向下
          if (nub == 1 && inx < thisArr.length - 1) {
            thisArr.splice(inx + 1, 1, ...thisArr.splice(inx, 1, thisArr[inx + 1]));
            okArr.splice(inx + 1, 1, ...okArr.splice(inx, 1, okArr[inx + 1]));
          } else if (nub != 1 && inx > 0) {
            thisArr.splice(inx, 1, ...thisArr.splice(inx - 1, 1, thisArr[inx]));
            okArr.splice(inx, 1, ...okArr.splice(inx - 1, 1, okArr[inx]));
          }
          this.targetData = okArr;
        }
      }

    },
    // /czc-community/patrol/point/list/point
    patrolPoint () {
      this.$http.get('/czc-community/patrol/point/list/point', { routeId: this.patrolDetail.id }).then(({ data, status, msg }) => {
        // debugger
        if (status == 0) {
          //  this.ruleForm.routePointRelationDtos
          this.ruleForm.routePointRelationDtos = [];
          data.map((item, index) => {
            this.ruleForm.routePointRelationDtos.push(item.pointId)
          })
          console.log('this.ruleForm.routePointRelationDtos', this.ruleForm.routePointRelationDtos);
        }
      })
    }

  },
  created () {
    if (JSON.stringify(this.patrolDetail) == "{}") {
      return;
    } else {

      this.ruleForm.communityId = this.patrolDetail.communityId;
      this.ruleForm.routeName = this.patrolDetail.routeName;
      this.effectiveDate[0] = this.patrolDetail.startDate;
      this.effectiveDate[1] = this.patrolDetail.endDate;
      this.timePeriod = [];
      let dataRes = this.patrolDetail.timePeriod.split(",");
      dataRes.map((item, index) => {
        this.timePeriod.push({
          startTime: (item).substr(0, 5),
          endTime: (item).substr(6, 5),
        })
      });
      this.ruleForm.periodType = this.patrolDetail.periodType;
      let data = [];
      this.periodValue = [];
      data = (this.patrolDetail.periodValue).split(",");
      data.map((item) => {
        this.periodValue.push(Number(item))
      });
      this.ruleForm.positioningDistance = this.patrolDetail.positioningDistance;
      this.ruleForm.cameraSettings = this.patrolDetail.cameraSettings;
      this.ruleForm.signFlag = this.patrolDetail.signFlag;
      this.ruleForm.remark = this.patrolDetail.remark;
      this.patrolPoint();
    }
  }
};
</script>
<style lang='scss' scoped>
@import '@assets/css/public-style.scss';
.main {
    padding: 20px;
    background: white;
    .blockName {
        padding-bottom: 20px;
        margin-bottom: 20px;
        border-bottom: 1px solid #e0e1e3;
    }
}

.show-required-icon-star {
    &:before {
        content: '*';
        color: #f56c6c;
    }
}

.formContent {
    display: flex;
    justify-content: space-between;
    .formContent-item {
        width: 49%;
    }
    .periodValueInput {
        color: #606266;
    }
    .sunm {
        width: 15px;
        text-align: center;
        display: inline-block;
        cursor: pointer;
        margin-left: 10px;
    }
    .timeList {
        margin-bottom: 10px;
        &:nth-last-child() {
            margin: 0;
        }
    }
}
.width50 {
    width: calc(50% - 40px);
    & + span {
        margin: 0 3px;
        display: inline-block;
    }
}
/deep/ .el-transfer-panel__item.el-checkbox {
    margin-right: 0;
}
.transferTudeClass {
    display: flex;
    justify-content: space-between;
    > div {
        width: 60px;
        display: flex;
        justify-content: space-around;
    }
    .zoniot_font {
        line-height: 30px;
    }
}
/deep/ .el-transfer-panel:first-child {
    .transferTudeClass {
        > div {
            display: none;
        }
    }
}
</style>
