<template>
  <a-modal class="CarWashModal" :title="mtitle" :width="1000" :footer="null" :destroyOnClose="true" @cancel="isShow=false" v-model="isShow">
    <!-- 表单 -->
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-model-item label="网点名称" prop="name">
            <a-input v-model="form.name" :maxLength="20" placeholder="请输入网店名称,20个字以内" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="地址" class="default-form-item form-item-required">
            <a-row :gutter="20">
              <a-col :span="8">
                <a-form-model-item prop="addrProvince">
                  <a-select v-model="form.addrProvince" placeholder="请选择省" @change="getCityList">
                    <a-select-option v-for="item in addrProvinceList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item prop="addrCity">
                  <a-select v-model="form.addrCity" placeholder="请选择市" @change="getAreaList">
                    <a-select-option v-for="item in addrCityList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item prop="addrDistrict">
                  <a-select v-model="form.addrDistrict" placeholder="请选择区" @change="areaCharged">
                    <a-select-option v-for="item in addrDistrictList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item label="详细地址" prop="addrDetail" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
            <a-input v-model="form.addrDetail" :maxLength="32" placeholder="请输入详细地址,32个字以内" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="设备ID" prop="deviceDTOList" class="default-form-item">
            <a-row :gutter="20">
              <a-col :span="19">
                <a-tag v-if="form.deviceDTOList.length > 0" color="blue">{{deviceNo}}</a-tag>
              </a-col>
              <a-col :span="5">
                <a-button type="primary" size="small" class="small-btn" @click="openEquipmentModal=true">选择</a-button>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="网点标签" prop="featuredServiceLabel" :rules="{required: true, message: '请选择网点标签', trigger: 'change'}">
            <v-select ref="featuredServiceLabel" v-model="featuredServiceLabel" @change="featuredServiceLabelChange" mode="multiple" placeholder="请选择网点标签" showArrow code="STORE_LABEL"></v-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="经度" prop="lng" class="default-form-item">
            <a-row :gutter="20">
              <a-col :span="17">
                <a-input v-model="form.lng" placeholder="请输入经度坐标" />
              </a-col>
              <a-col :span="6">
                <a href="https://lbs.qq.com/tool/getpoint/" target="_blank">
                  <a-button type="primary" size="small" icon="search" class="small-btn">查询坐标</a-button>
                </a>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="纬度" prop="lat">
            <a-input v-model="form.lat" placeholder="请输入纬度坐标" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="服务类型" prop="serviceType">
            <a-select v-model="form.serviceType" placeholder="请选择服务类型" @change="isResetstoreItemPriceDTOList('serviceType', $event)" showArrow mode="multiple">
              <a-select-option v-for="item in itemQueryList" :key="item.id" :value="item.id">{{item.itemName}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="营业时间" class="default-form-item form-item-required">
            <a-row :gutter="20">
              <a-col :span="11">
                <a-form-model-item prop="beginTime">
                  <a-time-picker v-model="form.beginTime" @change="isResetstoreItemPriceDTOList('beginTime', $event)" format="HH:mm" placeholder="请选择开始时间" class="time-picker" />
                </a-form-model-item>
              </a-col>
              <a-col :span="2">至</a-col>
              <a-col :span="11">
                <a-form-model-item prop="endTime">
                  <a-time-picker v-model="form.endTime" @change="isResetstoreItemPriceDTOList('endTime', $event)" format="HH:mm" placeholder="请选择结束时间" class="time-picker" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
        <!-- 时段价格设置  start -->
        <a-col :span="24">
          <a-form-model-item :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }" prop="storeItemPriceDTOList">
            <div slot="label" class="form-item-label">
              <a-tooltip placement="right" arrow-point-at-center title="时段价格是指车主在不同时段洗车需要支付不同的价格，主要用于日间服务和夜间服务的差异化管理，达到调节流量、集客引流的效果。不同时段区间采用起始时间包含，结束时间不包含原则。例如：时段区间为06:00（含）-22:00（不含），普通洗车10元；时间区间为22:00（含）-06:00（不含），普通洗车8元。客户在6点00分01秒普通洗车为10元，客户在22点00分01秒普通洗车为8元。">
                时段价格
                <a-icon :style="{ fontSize: '18px', color: '#1890ff', verticalAlign: 'sub' }" type="question-circle" />
              </a-tooltip>
            </div>
            <a-row :gutter="20" v-for="(item, ind) in form.storeItemPriceDTOList" :key="ind">
              <a-col :span="9">
                <a-row :gutter="20">
                  <a-col :span="11">
                    <a-form-model-item :prop="'storeItemPriceDTOList.'+ ind + '.beginTime'" :rules="{required: true, message: '请选择开始时间', trigger: 'change'}">
                      <a-time-picker v-model="item.beginTime" disabled format="HH:mm" placeholder="请选择" class="time-picker" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="2">至</a-col>
                  <a-col :span="11">
                    <a-form-model-item :prop="'storeItemPriceDTOList.'+ ind + '.endTime'" :rules="{required: true, message: '请选择结束时间', trigger: 'change'}">
                      <a-time-picker v-model="item.endTime" :default-open-value="item.beginTime" @change="isResetBelowstoreItemPriceDTOList($event, ind)" format="HH:mm" placeholder="请选择" class="time-picker" />
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :span="14">
                <a-row :gutter="20">
                  <a-col :span="8" v-for="(priceItem, subInd) in item.currentPrices" :key="subInd">
                    <a-form-model-item :prop="'storeItemPriceDTOList.'+ ind +'.currentPrices.'+ subInd + '.price'" :rules="{required: true, message: `请输入【${priceItem.name}】单价`, trigger: 'blur'}">
                      <!-- <a-input v-model="priceItem.price" :placeholder="'【'+ priceItem.name +'】单价'" suffix="元" /> -->
                      <a-input-number v-model="priceItem.price" :min="0" :max="999999" :placeholder="'【'+ priceItem.name +'】单价'" class="input-number-s" />
                      <span class="unit">元</span>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :span="1">
                <a-icon type="delete" title="删除" @click="delstoreItemPriceDTOList(ind)" :style="{ fontSize: '20px', color: 'red' }" />
              </a-col>
            </a-row>
            <a-button type="dashed" @click="setTimeInterval" class="setTimeInterval"><a-icon type="plus" />添加时段</a-button>
          </a-form-model-item>
        </a-col>
        <!-- 时段价格设置  end -->
        <a-col :span="24">
          <a-form-model-item label="路线指引" prop="guidance" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
            <editor ref="editor" @on-change="editorChange" :cache="false" v-model="form.guidance"></editor>
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item label="温馨提示" prop="reminder" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
            <a-textarea ref="reminder" v-model="form.reminder" :maxLength="128" :auto-size="{ minRows: 3, maxRows: 5 }" placeholder="请输入温馨提示,128个字以内" />
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }" class="btn-cont">
            <a-button type="primary" @click="onSubmit('ruleForm')">保存</a-button>
            <a-button class="resetForm" @click="resetForm">取消</a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    
    <!-- 选择设备 -->
    <choose-equipment
      :openEquipmentModal="openEquipmentModal"
      @close="closeChooseEquipment"
    />
    
  </a-modal>
</template>

<script>
  import { VSelect } from '@/components'
  import ChooseEquipment from './ChooseEquipment.vue'
  import Editor from '@/components/WEeditor'
  import moment from 'moment'
  import { getProvince, getCityByPro, getDistrictByCity } from '@/api/lookup'
  import { itemQuery, storeSave } from '@/api/car-wash'
  export default{
    name: 'AddCarWashModal',
    components: { VSelect, Editor, ChooseEquipment },
    props: {
      openModal: {  //  弹框是否展示
        type: Boolean,
        default: false
      },
      mtitle: {  //  弹框标题
        type: String,
        default: ''
      },
      carWashInfo: {  //  网点详情
        type: Object,
        default: ()=>{}
      }
    },
    data(){
      return{
        isShow: this.openModal,  //  弹框是否展示
        form: {
          name: '',  //  网点名称
          addrProvince: undefined,  //  省  编码
          addrProvinceName: '',  //  省
          addrCity: undefined,  //  市  编码
          addrCityName: '',  //  市
          addrDistrict: undefined,  //  区  编码
          addrDistrictName: '',  //  区
          addrDetail: '',  //  详细地址
          deviceDTOList: [],  //  设备序列号
          featuredServiceLabel: '',  //  网点标签
          lng: '',  //  经度
          lat: '',  //  纬度
          serviceType: [],  //  服务类型
          beginTime: null,  //  营业时间开始时间
          endTime: null,  //  营业时间结束时间
          storeItemPriceDTOList: [],  //  时段价格
          guidance: '',  //  路线指引
          reminder: ''  //  温馨提示
        },
        rules: {
          name: [
            { required: true, message: '请输入网店名称', trigger: 'blur' }
          ],
          addrProvince: [
            { required: true, message: '请选择所在省份', trigger: 'change' }
          ],
          addrCity: [
            { required: true, message: '请选择所在市', trigger: 'change' }
          ],
          addrDistrict: [
            { required: true, message: '请选择所在区县', trigger: 'change' }
          ],
          addrDetail: [
            { required: true, message: '请输入详细地址', trigger: 'blur' }
          ],
          deviceDTOList: [
            { required: true, message: '请选择设备', trigger: 'change' }
          ],
          lng: [
            { required: true, message: '请输入经度', trigger: 'blur' }
          ],
          lat: [
            { required: true, message: '请输入纬度', trigger: 'blur' }
          ],
          serviceType: [
            { required: true, message: '请选择服务类型', trigger: 'change' }
          ],
          beginTime: [
            { required: true, message: '请选择开始时间', trigger: 'change' }
          ],
          endTime: [
            { required: true, message: '请选择结束时间', trigger: 'change' }
          ],
          storeItemPriceDTOList: [
            { required: true, message: '请设置时段价格', trigger: 'change' }
          ]
        },
        openEquipmentModal: false  ,//  选择设备  弹框展示状态
        serviceType: [],  //  服务类型  change前的值
        beginTime: null,  //  营业时间开始时间  change前的值
        endTime: null,  //  营业时间结束时间  change前的值
        subendTime: [],  //  时段价格  时段区间结束时间  change前的值
        featuredServiceLabel: [],  //  网点标签
        addrProvinceList: [],  //  省列表数据
        addrCityList: [],  //  市列表数据
        addrDistrictList: [],  //  区县列表数据
        itemQueryList: [],  //  服务类型列表数据
        deviceNo: '',  //  已选设备序列号
      }
    },
    methods: {
      moment,
      // 文本编辑器  change
      editorChange (html, text) {
        console.log(html, text,'===')
        this.form.guidance = html
        // 点击查看详情时给文本编辑器赋值
      },
      //  表单赋值
      setVal(item){
        const _this = this
        console.log(item)
        let arr = [
          'name',
          'addrProvince',
          'addrProvinceName',
          // 'addrCity',
          'addrCityName',
          // 'addrDistrict',
          'addrDistrictName',
          // 'addrDetail',
          // 'deviceDTOList',
          'featuredServiceLabel',
          'lng',
          'lat',
          'serviceType',
          // 'beginTime',
          // 'endTime',
          // 'storeItemPriceDTOList',
          'guidance',
          'reminder'
        ]
        arr.map(k => {
          this.form[k] = item[k]
        })
        // this.form.addrProvince = item.addrProvince
        this.getCityList(item.addrProvince)  //  获取市区下拉数据
        this.form.addrCity = item.addrCity  //  市区赋值
        this.getAreaList(item.addrCity)  //  获取区县下拉数据
        this.form.addrDistrict = item.addrDistrict  //  区县赋值
        this.form.addrDetail = item.addrDetail  //  详细地址赋值
        this.form.deviceDTOList = [{id: item.deviceVOList[0].id}]  //  设备
        this.deviceNo = item.deviceVOList[0].deviceNo  //  设备序列号
        this.featuredServiceLabel = item.featuredServiceLabel.split(',')  //  网点标签
        this.form.serviceType = 
        
        
        this.$refs.editor.setHtml(item.guidance)  //  文本编辑器赋值
      },
      //  保存
      onSubmit(formName){
        const _this = this
        _this.$refs[formName].validate(valid => {
          if (valid) {
            let formData = JSON.parse(JSON.stringify(_this.form))
            //  校验营业时间结束时间是否与时段价格一致
            let endTime = formData.storeItemPriceDTOList[formData.storeItemPriceDTOList.length - 1].endTime
            if(_this.timeFormat(formData.endTime) != _this.timeFormat(endTime)){
              _this.$message.error('时段价格与营业时间不一致，请修改后再保存！')
              return
            }
            formData.beginTime = _this.timeFormat(formData.beginTime) + ':00'
            formData.endTime = _this.timeFormat(formData.endTime) + ':00'
            formData.storeItemPriceDTOList.map(item => {
              item.beginTime = _this.timeFormat(item.beginTime) + ':00'
              item.endTime = _this.timeFormat(item.endTime) + ':00'
              let arr = []
              item.currentPrices.map(k => {
                arr.push(Number(k.price))
              })
              item.currentPrices = arr
            })
            //  提交前时间格式还需转换
            delete formData.serviceType
            storeSave(formData).then(res => {
              if(res.status == 200){
                _this.$message.success(res.message)
                _this.$emit('success')
              }else{
                _this.$message.error(res.message)
              }
            })
          } else {
            return false
          }
        })
      },
      // 时间格式转换
      timeFormat (time) {
        const dateTime = new Date(time)
        const hour = dateTime.getHours()
        const minute = dateTime.getMinutes()
        let timeStr = this.addZero(hour) + ':' + this.addZero(minute)
        return timeStr
      },
      // 时间0补位
      addZero (v) {
        return v < 10 ? '0' + v : v
      },
      // 取消
      resetForm(){
        this.$refs.ruleForm.resetFields()
        this.isShow = false
      },
      // 是否重置时段价格 (更改服务类型、营业开始结束时间)
      isResetstoreItemPriceDTOList(type, val){
        // type: serviceType  服务类型  beginTime  营业时间  开始时间  endTime  营业时间  结束时间
        const _this = this
        setTimeout(()=>{
          if(_this.form.storeItemPriceDTOList.length != 0){
            _this.$confirm({
              title: '提示',
              content: '更改后已设置的时段价格将会全部清空，确定要更改吗？',
              onOk() {
                type == 'serviceType' ? _this.serviceType = val : type == 'beginTime' ? _this.beginTime = val : _this.endTime = val
                _this.form.storeItemPriceDTOList = []
              },
              onCancel() {
                type == 'serviceType' ? _this.form.serviceType = _this.serviceType : type == 'beginTime' ? _this.form.beginTime = _this.beginTime : _this.form.endTime = _this.endTime
              },
            })
          }else{
            type == 'serviceType' ? _this.serviceType = val : type == 'beginTime' ? _this.beginTime = val : _this.endTime = val
          }
        },0)
      },
      // 是否重置时段价格 (更改时段价格区间结束时间)
      isResetBelowstoreItemPriceDTOList(val, ind){
        const _this = this
        // 更改已设置过的时段时间（因为有下一个时段的前提是当前时段结束时间已设置）
        if(this.form.storeItemPriceDTOList[ind + 1]){
          _this.$confirm({
            title: '提示',
            content: '更改已设置过的时段区间，其之后的时段区间将会被清空，确定要更改吗？',
            onOk() {
              _this.subendTime[ind] = val
              _this.form.storeItemPriceDTOList.splice(ind + 1, _this.form.storeItemPriceDTOList.length - Number(ind + 1))
            },
            onCancel() {
              _this.form.storeItemPriceDTOList[ind].endTime = _this.subendTime[ind]
            },
          })
        }else{
          _this.subendTime[ind] = val
        }
      },
      //  选择设备
      closeChooseEquipment(val, no){
        if(val){
          this.form.deviceDTOList = [{id: val}]
          this.deviceNo = no
        }
        this.openEquipmentModal = false
      },
      //  设置时段价格
      setTimeInterval(){
        if(this.form.serviceType.length == 0){
          this.$message.error('请先选择服务类型')
          return
        }
        if(!this.form.beginTime){
          this.$message.error('请先选择营业时间开始时间')
          return
        }
        if(!this.form.endTime){
          this.$message.error('请先选择营业时间结束时间')
          return
        }
        let arr = {}
        // 时段价格开始时间
        let timeStr = ''
        if(this.form.storeItemPriceDTOList.length == 0){
          timeStr = this.form.beginTime.format('HH:mm')
        }else{
          timeStr = this.form.storeItemPriceDTOList[this.form.storeItemPriceDTOList.length - 1].endTime
          if(!timeStr){
            this.$message.error('请先选择时段价格 - 第'+ this.form.storeItemPriceDTOList.length +'个时段的结束时间')
            return
          }
        }
        arr.beginTime = moment(timeStr, 'HH:mm')
        arr.endTime = null
        arr.itemIds = this.form.serviceType
        arr.currentPrices = []
        this.form.serviceType.map((item, index) => {
          let i = this.itemQueryList.findIndex(k => k.id == item)
          arr.currentPrices.push({ name: this.itemQueryList[i].itemName, price: '' })
        })
        this.form.storeItemPriceDTOList.push(arr)
      },
      // 删除时段价格
      delstoreItemPriceDTOList(ind){
        const _this = this
        let msg = Number(ind + 1) == _this.form.storeItemPriceDTOList.length ? '确定要删除该时段吗？' : '确定要删除该时段以及其之后已设置的时段吗？'
        _this.$confirm({
          title: '提示',
          content: msg,
          onOk() {
            _this.form.storeItemPriceDTOList.splice(ind, _this.form.storeItemPriceDTOList.length - ind)
          }
        })
      },
      // 网点标签  change
      featuredServiceLabelChange(val){
        this.form.featuredServiceLabel = val.join(',')
      },
      // 获取服务类型列表
      getItemQuery(){
        itemQuery({
          pageNo: 1,
          pageSize: 1000
        }).then(res => {
          if(res.status == 200){
            this.itemQueryList = res.data.list || []
          }else{
            this.itemQueryList = []
          }
        })
      },
      // 获取省列表'
      getProvinceList() {
        const _this = this
        getProvince().then(res => {
          if (res.status == 200) {
            _this.addrProvinceList = res.data || []
          } else {
            _this.addrProvinceList = []
          }
        })
      },
      // 获取城市列表
      getCityList (val) {
        this.addrCityList = []
        this.addrDistrictList = []
        this.form.addrCity = undefined
        this.form.addrDistrict = undefined
        this.form.addrDetail = ''
        if (val == null || val == '') {
          this.form.addrProvinceName = ''
        } else {
          for (let i = 0; i < this.addrProvinceList.length; i++) {
            if (this.addrProvinceList[i].id == val) {
              this.form.addrProvinceName = this.addrProvinceList[i].name
              break
            }
          }
          this.getCityListRequest(val)
        }
      },
      getCityListRequest (val) {
        const _this = this
        getCityByPro({id: val}).then(res => {
          if (res.status == 200) {
            _this.addrCityList = res.data || []
          } else {
            _this.addrCityList = []
          }
        })
      },
      // 获取区县列表
      getAreaList (val) {
        this.addrDistrictList = []
        this.form.addrDistrict = undefined
        this.form.addrDetail = ''
        if (val == null || val == '') {
          this.form.addrCityName = ''
        } else {
          for (let i = 0; i < this.addrCityList.length; i++) {
            if (this.addrCityList[i].id == val) {
              this.form.addrCityName = this.addrCityList[i].name
              break
            }
          }
          this.getAreaListRequest(val)
        }
      },
      getAreaListRequest (val) {
        const _this = this
        getDistrictByCity({id: val}).then(res => {
          if (res.status == 200) {
            _this.addrDistrictList = res.data || []
          } else {
            _this.addrDistrictList = []
          }
        })
      },
      // 区县变更
      areaCharged (val) {
        if (val == null || val == '') {
          this.form.addrDistrictName = ''
        } else {
          for (let i = 0; i < this.addrDistrictList.length; i++) {
            if (this.addrDistrictList[i].id == val) {
              this.form.addrDistrictName = this.addrDistrictList[i].name
              break
            }
          }
        }
        this.form.addrDetail = ''
      }
    },
    watch: {
      //  父页面传过来的弹框状态
      openModal (newValue, oldValue) {
        this.isShow = newValue
      },
      //  重定义的弹框状态
      isShow (val){
        if (!val){
          this.$emit('close')
        }else{
          this.getProvinceList()  //  获取省下拉
          this.getItemQuery()  //  服务类型  列表
        }
      },
      // 网点详情  数据
      carWashInfo: {
        handler: function (item) {
          this.setVal(item)
        },
        deep: true
      }
    }
  }
</script>

<style lang="less">
  .CarWashModal{
    .default-form-item{
      margin-bottom: 0;
    }
    .form-item-label{
        display: inline-block;
        cursor: pointer;
    }
    .form-item-required{
      .ant-form-item-label{
        label:before{
          display: inline-block;
          margin-right: 4px;
          color: #f5222d;
          font-size: 14px;
          font-family: SimSun, sans-serif;
          line-height: 1;
          content: '*';
        }
      }
    }
    .small-btn{
      background-color: #19be6b;
      font-size: 13px;
    }
    .small-btn.ant-btn-primary:focus, .small-btn.ant-btn-primary:hover{
      background-color: #19be6b;
    }
    .time-picker{
      width: 100%;
    }
    .btn-cont{
      text-align: center;
      .resetForm{
        margin-left: 10px;
      }
    }
    .setTimeInterval{
      width: 40%;
      color: #19be6b;
    }
    .input-number-s{
      width: 90%;
    }
    .unit{
      display: inline-block;
      width: 10%;
      text-align: right;
    }
  }
</style>
