<template>
  <view class="fullHeight">
    <headers :showBack="true">
      <view class="headerName">
        {{ pageTitle }}
      </view>
    </headers>
    <view class="formBox">
      <form @submit="formSubmit">

        <view class="uni-form-item">
          <view class="uni-form-label">
            企业
          </view>
          <!-- enterpriseId -->
          <view class="uni-form-input">
            <picker @change="bindPickerChange5" :value="selectIndexQy" :range="qyList"
                    range-key="enterpriseName">
              <view class="uni-input uni-select cl" v-if="selectIndexQy==null">
                请选择
                <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
              </view>
              <view class="uni-input uni-select" v-else>{{ qyList[selectIndexQy].enterpriseName }}
                <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
              </view>
            </picker>
          </view>
        </view>
        <view class="uni-form-item">
          <view class="uni-form-label">
            <text class="star">*</text>
            固定/临时车辆
          </view>
          <view class="uni-form-input">
            <u-radio-group v-model="form.carModuleType">
              <u-radio :name="1">
                固定车辆
              </u-radio>
              <u-radio :name="2">
                临时车辆
              </u-radio>
            </u-radio-group>
          </view>
        </view>
        <view class="uni-form-item" v-show="form.carModuleType==2">
          <view class="uni-form-label">
            <text class="star">*</text>
            预约开始时间
          </view>
          <view class="uni-form-input">
            <view class="uni-input def" :class="{text:form.reserveStartTime}"
                  @click="showTime=true;key='reserveStartTime'">
              {{ form.reserveStartTime || '请选择' }}
            </view>
            <u-picker mode="time" v-model="showTime" :params="params" @confirm="confirm"></u-picker>
          </view>
        </view>
        <view class="uni-form-item" v-show="form.carModuleType==2">
          <view class="uni-form-label">
            <text class="star">*</text>
            预约结束时间
          </view>
          <view class="uni-form-input">
            <view class="uni-input def" :class="{text:form.reserveEndTime}" @click="showTime=true;key='reserveEndTime'">
              {{ form.reserveEndTime || '请选择' }}
            </view>
          </view>
        </view>
        <view class="uni-form-item" v-show="form.carModuleType==2">
          <view class="uni-form-label">
            <text class="star">*</text>
            允许进出入次数
          </view>
          <view class="uni-form-input">
            <u-radio-group v-model="form.entryAndExitPermit">
              <u-radio :name="0">
                单次
              </u-radio>
              <u-radio :name="1">
                多次
              </u-radio>
            </u-radio-group>
          </view>
        </view>
        <view class="uni-form-item">
          <view class="uni-form-label">
            <text class="star">*</text>
            车牌号
          </view>
          <view class="uni-form-input">
            <input class="uni-input" placeholder-class="cl" name="carNumber" :value="form.carNumber"
                   placeholder="请输入"/>
          </view>
        </view>
        <view class="uni-form-item">
          <view class="uni-form-label">
            车牌照片
          </view>
          <view class="uni-form-input" style="display: inline-flex;">
            <view class="imgBox" v-show="form.carPhotosUrl">
              <image :src="url_config+'image/'+form.carPhotosUrl" class="img"></image>
              <uni-icons @click="deleteImg" class="deleteImg" type="clear" size="24"></uni-icons>
            </view>
            <view class="addImgBox" @click="selectImg">
              <image src="/static/icon-add.png" class="icon-add"></image>
            </view>
          </view>
        </view>
        <view class="uni-form-item">
          <view class="uni-form-label">
            <text class="star">*</text>
            车辆颜色
          </view>
          <view class="uni-form-input">
            <picker @change="bindPickerChange" :value="selectIndex" :range="colorList"
                    range-key="locationName">
              <view class="uni-input uni-select cl" v-if="selectIndex==null">
                请选择
                <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
              </view>
              <view class="uni-input uni-select" v-else>{{ colorList[selectIndex] }}
                <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
              </view>
            </picker>
          </view>
        </view>
        <view class="uni-form-item">
          <view class="uni-form-label">
            <text class="star">*</text>
            车辆类型
          </view>
          <view class="uni-form-input">
            <picker @change="bindPickerChange2" :value="carTypeIndex" :range="carTypeList"
                    range-key="carTypeName">
              <view class="uni-input uni-select cl" v-if="carTypeIndex==null">
                请选择
                <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
              </view>
              <view class="uni-input uni-select" v-else>{{ carTypeList[carTypeIndex].carTypeName }}
                <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
              </view>
            </picker>
          </view>
        </view>

        <view class="uni-form-item">
          <view class="uni-form-label">
            <text class="star">*</text>
            司机姓名
          </view>
          <view class="uni-form-input">
            <picker @change="bindPickerChange3" :value="driverNameIndex" :range="driverNameList"
                    range-key="workerName">
              <view class="uni-input uni-select cl" v-if="driverNameIndex==null">
                请选择
                <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
              </view>
              <view class="uni-input uni-select" v-else>{{ driverNameList[driverNameIndex].workerName }}
                <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
              </view>
            </picker>
          </view>
          <!-- <view class="uni-form-input">
            <input class="uni-input" placeholder-class="cl" name="driverName" :value="form.driverName"
              placeholder="请输入" />
          </view> -->
        </view>
        <view class="uni-form-item">
          <view class="uni-form-label">
            <text class="star">*</text>
            司机电话
          </view>
          <view class="uni-form-input">
            <input class="uni-input" placeholder-class="cl" name="driverTelephone"
                   :value="form.driverTelephone" placeholder="请输入"/>
          </view>
        </view>
        <view class="uni-form-item">
          <view class="uni-form-label">
            <text class="star">*</text>
            是否黑名单
          </view>
          <view class="uni-form-input">
            <radio-group @change="radioChange" name="isBlack">
              <label style="margin-right: 15px;" class="radio">
                <radio value="0" :checked="form.isBlack==0"/>
                白名单
              </label>
              <label class="radio">
                <radio value="1" :checked="form.isBlack==1"/>
                黑名单
              </label>
            </radio-group>
          </view>
        </view>
        <view class="uni-form-item">
          <view class="uni-form-label">
            报警推送人
          </view>
          <view class="uni-form-input" @click="open">
            <!--            <picker @change="bindPickerChange4" :value="bjIndex" :range="baoList" range-key="workerName">-->
            <view class="uni-input uni-select cl" v-if="!filterArr">
              请选择
              <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
            </view>
            <view class="uni-input uni-select" v-else>{{ filterArr }}
              <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
            </view>
            <!--            </picker>-->
          </view>
        </view>
        <button form-type="submit" type="primary" class="btn submitBtn big">保存</button>
        <button class="btn deleteBtn" v-show="!isAdd" @click="deleteFn">删除</button>
      </form>
    </view>
    <uni-popup ref="cityMore" type="bottom">
      <view class="checkList">
        <view class="header">
          <view class="title">选择报警推送人</view>
          <view class="ok" @click="$refs.cityMore.close()">确认</view>
        </view>
        <scroll-view scroll-y="true" class="scroll-Y">
          <checkbox-group @change="checkChange">
            <view class="checkItem" v-for="(item,index) in baoList" :key="index">
              <view class="name">{{ item.workerName }}</view>
              <view class="check">
                <checkbox :value="item" :checked="cityIdArr.map(item => item.workerId).includes(item.workerId)"/>
              </view>
            </view>
          </checkbox-group>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      pageTitle: '新增车辆',
      selectIndex: null,
      colorList: ['蓝色', '绿色', '黄色', '白色', '黑色'],
      carTypeList: [],
      carTypeIndex: null,
      driverNameList: [],
      driverNameIndex: null,
      form: {
        carModuleType: 1,
        carColor: "",
        carNumber: "",
        carPhotosUrl: "",
        carType: "",
        driverName: "",
        driverTelephone: "",
        isBlack: '',
        projectSn: ''
      },
      personList: [],
      projectDetail: {},
      isAdd: true,
      baoList: [],
      bjIndex: null,
      showTime: false,
      params: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: true
      },
      key: '',
      selectIndexQy: null,
      qyList: [],
      cityIdArr: []
    }
  },
  computed: {
    filterArr() {
      let value = this.cityIdArr;
      try {
        if (value) {
          return value.map(item => item.workerName).join(',')
        }
      } catch (e) {
        return ""
      }
    },
    filterArrValue() {
      let value = this.cityIdArr;
      try {
        if (value) {
          return value.map(item => item.id).join(',')
        }
      } catch (e) {
        return ""
      }
    },

  },
  async onLoad(options) {
    this.projectDetail = JSON.parse(uni.getStorageSync('projectDetail'))


    await this.getCarTypeList()
    await this.getDriverNameList();
    await this.getProjectChilderSystemUserList();
    await this.enterpriseInfoList(() => {
      if (options.id) {
        this.isAdd = false
        this.pageTitle = '编辑车辆'
        this.getDetails(options.id)
      }
    });


  },

  methods: {
    checkChange(e) {
      console.log(e.detail.value)
      this.cityIdArr = e.detail.value
    },
    open() {
      this.$refs.cityMore.open()
    },
    confirm(e) {
      console.log(e)
      let {
        year,
        month,
        day,
        hour,
        minute,
        second
      } = e;
      this.form[this.key] = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    deleteFn() {
      var that = this
      uni.showModal({
        title: '提示',
        content: '确定删除该车辆吗？',
        success(res) {
          if (res.confirm) {
            that.sendRequest({
              url: 'xmgl/carInfo/delete',
              data: {
                id: that.form.id
              },
              method: "POST",
              success(res) {
                uni.showToast({
                  title: '删除成功！'
                })

                uni.navigateBack({})


                setTimeout(() => {
                  that.$router.go(0)
                }, 500)
              }
            })
          }
        }
      })
    },
    selectImg() {
      var that = this
      uni.chooseImage({
        count: 1,
        success(res) {
          const tempFilePaths = res.tempFilePaths;
          uni.uploadFile({
            url: that.url_config + 'upload/image', //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            name: 'files',
            success: (uploadFileRes) => {
              console.log(uploadFileRes.data);
              that.form.carPhotosUrl = JSON.parse(uploadFileRes.data).data[0]
                  .imageUrl
            }
          });
        }
      })
    },
    deleteImg() {
      this.form.carPhotosUrl = ''
    },
    radioChange(e) {
      this.form.isBlack = e.target.value
    },
    //获取司机姓名
    getDriverNameList() {
      var that = this
      this.sendRequest({
        url: 'xmgl/workerInfo/selectWorkerInfoList',
        data: {
          projectSn: this.projectDetail.projectSn,
          inserviceType: 1,
          pageNo: 1,
          pageSize: -1
        },
        method: "POST",
        success(res) {
          console.log(res, '车辆数据')
          that.driverNameList = res.result.records
          if (!that.isAdd) {
            for (var i = 0; i < res.result.records.length; i++) {
              if (that.form.driverWorkerId == res.result.records[i].id) {
                that.driverNameIndex = i;
                break;
              }
            }
          }
        }
      })
    },
    //获取车种
    getCarTypeList() {
      var that = this
      this.sendRequest({
        url: 'xmgl/carType/list',
        data: {
          projectSn: this.projectDetail.projectSn
        },
        method: "POST",
        success(res) {
          that.carTypeList = res.result
          if (!that.isAdd) {
            for (var i = 0; i < res.result.length; i++) {
              if (that.form.carType == res.result[i].id) {
                that.carTypeIndex = i;
                console.log(that.carTypeIndex, 12346)
                break;
              }
            }
          }
        }
      })
    },
    async getDetails(id) {
      var that = this
      await this.sendRequest({
        url: 'xmgl/carInfo/queryById',
        data: {
          id: id
        },
        method: "POST",
        success: (res) => {
          that.form = res.result
          that.selectIndex = that.colorList.indexOf(that.form.carColor)
          let enterpriseId = that.qyList.map(item => item.enterpriseId).indexOf(that.form
              .enterpriseId)
          that.selectIndexQy = enterpriseId >= 0 ? enterpriseId : null;
          let carTypeIndex = that.carTypeList.map(item => item.id).indexOf(that.form
              .carType)
          that.carTypeIndex = carTypeIndex >= 0 ? carTypeIndex : null;
          // let bjIndex = that.baoList.map(item => item.workerId).indexOf(that.form
          //     .alarmPushWorkerId)
          // that.bjIndex = bjIndex >= 0 ? bjIndex : null;

          // alarmPushWorkerId
          let idArr = this.form.alarmPushWorkerId.split(',');
          console.log(idArr, "idArridArridArr")
          that.cityIdArr = that.baoList.filter(item => {
            return idArr.includes(item.id)
          });

          let driverNameIndex = that.driverNameList.map(item => item.id).indexOf(that.form
              .driverWorkerId)
          that.driverNameIndex = driverNameIndex >= 0 ? driverNameIndex : null;

          if (that.form.carPhotosUrl) {
            var arr = JSON.parse(that.form.carPhotosUrl)
            if (arr.length > 0) {
              that.form.carPhotosUrl = arr[0].url
            } else {
              that.form.carPhotosUrl = ''
            }
          } else {
            that.form.carPhotosUrl = ''
          }
        }
      })
    },
    getProjectChilderSystemUserList() {
      var that = this
      this.sendRequest({
        url: 'xmgl/systemUser/getProjectChilderSystemUserList',
        data: {
          projectSn: this.projectDetail.projectSn
        },
        method: "POST",
        success(res) {
          console.log(res, "报警")
          that.baoList = res.result.map(item => {
            item.name = item.workerName
            return item
          });
        }
      })
    },
    enterpriseInfoList(next) {
      var that = this
      this.sendRequest({
        url: 'xmgl/enterpriseInfo/list',
        data: {
          projectSn: this.projectDetail.projectSn
        },
        method: "POST",
        success(res) {
          that.qyList = res.result;
          next()
        }
      })
    },
    bindPickerChange: function (e) {
      this.selectIndex = e.target.value
    },
    bindPickerChange2: function (e) {
      this.carTypeIndex = e.target.value
    },
    bindPickerChange3: function (e) {
      this.driverNameIndex = e.target.value
    },
    bindPickerChange4: function (e) {
      this.bjIndex = e.target.value
    },
    bindPickerChange5: function (e) {
      this.selectIndexQy = e.target.value
    },
    bindDateChange: function (e) {
      this.form.eduTime = e.target.value
    },
    formSubmit(e) {
      var that = this
      console.log(e)
      var params = e.detail.value
      params.projectSn = this.projectDetail.projectSn;

      params.entryAndExitPermit = this.form.entryAndExitPermit;

      if (this.selectIndex == null) {
        uni.showToast({
          title: '请选择车辆颜色',
          icon: 'none'
        })
        return false;
      }
      if (this.carTypeIndex == null) {
        uni.showToast({
          title: '请选择车辆类型',
          icon: 'none'
        })
        return false;
      }
      if (this.driverNameIndex == null) {
        uni.showToast({
          title: '请选择司机姓名',
          icon: 'none'
        })
        return false;
      }
      if (params.carNumber == '') {
        uni.showToast({
          title: '请输入车牌号',
          icon: 'none'
        })
        return false;
      }
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (params.driverTelephone == '') {
        uni.showToast({
          title: '请输入司机电话',
          icon: 'none'
        })
        return false;
      } else if (!reg.test(params.driverTelephone)) {
        uni.showToast({
          title: '电话格式错误',
          icon: 'none'
        })
        return false;
      }
      if (params.isBlack == '') {
        uni.showToast({
          title: '请选择是否黑名单',
          icon: 'none'
        })
        return false;
      }
      if (this.form.carPhotosUrl) {
        params.carPhotosUrl = JSON.stringify([{
          name: '',
          url: this.form.carPhotosUrl
        }])
      }
      params.carColor = this.colorList[this.selectIndex]
      if (this.driverNameList[this.driverNameIndex]) {
        params.driverWorkerId = this.driverNameList[this.driverNameIndex].id
      }
      if (this.filterArrValue) {
        params.alarmPushWorkerId = this.filterArrValue;
      }
      if (this.carTypeList[this.carTypeIndex]) {
        params.carType = this.carTypeList[this.carTypeIndex].id
      }
      params.carModuleType = this.form.carModuleType
      if (this.qyList[this.selectIndexQy]) {
        params.enterpriseId = this.qyList[this.selectIndexQy].enterpriseId
      }

      if (this.form.carModuleType == 2) {
        params.isBlack = '0';
        if (this.form.reserveStartTime) {
          params.reserveStartTime = this.form.reserveStartTime
        } else {
          uni.showToast({
            title: '请选择预约开始时间',
            icon: 'none'
          })
          return false;
        }
        if (this.form.reserveEndTime) {
          params.reserveEndTime = this.form.reserveEndTime
        } else {
          uni.showToast({
            title: '请选择预约结束时间',
            icon: 'none'
          })
          return false;
        }
      }
      var url = 'xmgl/carInfo/edit'
      if (this.isAdd) {
        url = 'xmgl/carInfo/add'
      } else {
        params.id = this.form.id
      }

      console.log(params, "params");

      this.sendRequest({
        url: url,
        data: params,
        method: "POST",
        success(res) {
          uni.showToast({
            title: '保存成功！'
          })
          // uni.navigateBack({

          // })
          uni.navigateTo({
            url: './index'
          });

        }

      })
    }
  }
}
</script>

<style lang="scss" scoped>
.addImgBox {
  border: 1px solid rgba(42, 43, 91, 0.1);
  background-color: #f6f5f8;
  width: 60px;
  height: 60px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  font-size: 12px;

  .icon-add {
    width: 18px;
    height: 18px;
  }
}

.uni-input {
  &.def {
    color: #ddd;
  }

  &.text {
    color: #372D66;
  }
}

.imgBox {
  width: 60px;
  height: 60px;
  display: inline-flex;
  position: relative;
  margin-right: 15px;

  .img {
    width: 100%;
    height: 100%;
    border-radius: 10px;
  }

  .deleteImg {
    position: absolute;
    right: -10px;
    top: -10px;
  }
}

.checkList {
  background-color: #fff;


  .scroll-Y {
    height: 600rpx;
  }

  .header {
    display: flex;
    justify-content: space-between;
    border-bottom: 1rpx solid #ddd;
    padding: 20rpx;

    .title {
      font-weight: 500;
    }

    .ok {
      color: $uni-color-primary;
    }
  }


}

.checkItem {
  display: flex;
  padding: 20rpx;

  .name {
    flex: 1;
    margin-right: 20rpx;
  }

  .check {

  }
}
</style>
