<template>
  <sail-page type="maintenanceApply" title="维保申请" isHead>
    <div style="height: 95vh" slot="content" :class="repairForm.id !== 0 ? 'has-id': ''">
        <statusModal type="maintenance" title="维保申请" isButton isHead desc="申请成功" @jumpCallback="jumpCallback" btxt="查看申请">
           <div slot="up-content">
              <p>恭喜您， 申请成功</p>
              <p>我们的维保人员会尽快联系您，请保持通话畅通。</p>
           </div>
           <div slot="down-content">
              <p>维保编号：{{repairCode}} </p>
              <p>维保类型：{{selectedTypeName}}</p>
              <p>上门时间：{{selectedTime}}</p>
           </div>
        </statusModal>
        <div class="maintenance-apply-wrapper">
          <p class="maintenance-desc">请认真详细的描述出您的问题，以便我们更好的为您服务。</p>
          <div class="maintenance-form">
            <div class="weui-cells zero-top">
                <div class="weui-cell">
                    <div class="weui-cell__hd"><label class="weui-label">姓名</label></div>
                    <div class="weui-cell__bd">
                        <input :disabled="repairForm.id !== 0" v-model="repairForm.applicantName" class="weui-input" type="text" placeholder="请输入姓名">
                    </div>
                </div>
                <div class="weui-cell">
                        <div class="weui-cell__hd"><label class="weui-label">联系方式</label></div>
                        <div class="weui-cell__bd">
                            <input :disabled="repairForm.id !== 0" v-model="repairForm.applicantPhone" class="weui-input" type="number" pattern="[0-9]*" placeholder="请输入联系方式">
                        </div>
                </div>
                <div v-if="repairForm.id === 0" @click="onRepairTypeClick">
                  <van-cell-group class="spec-placeholder">
                    <van-field :value="selectedTypeName" disabled center label="维保类型" placeholder="请选择">
                      <van-icon slot="icon" name="arrow" />
                    </van-field>
                  </van-cell-group>
                </div>
                <div v-if="repairForm.id !== 0">
                  <van-cell-group class="spec-placeholder">
                    <van-field :value="selectedTypeName" disabled center label="维保类型" placeholder="请选择">
                      <van-icon slot="icon" name="arrow" />
                    </van-field>
                  </van-cell-group>
                </div>
                <div v-show="!(selectedTypeName && selectedTypeName.indexOf('公共区域维保') > -1)" @click="onDoorClick">
                  <van-cell-group class="spec-placeholder">
                    <van-field :value="selectedTime" disabled center label="上门时间" placeholder="请选择">
                      <van-icon slot="icon" name="arrow" />
                    </van-field>
                  </van-cell-group>
                </div>
            </div>
            <van-cell-group class="maintenance-part">
              <van-field
                v-model="repairForm.remark"
                label="备注"
                :disabled="repairForm.id !== 0"
                type="textarea"
                autosize
                placeholder="请填写备注"
                rows="1"
/>
            </van-cell-group>
            <div class="maintenance-min-part">
              <cube-upload
                :action="action"
                v-model="files"
                :simultaneous-uploads="1"
                @file-success="successHandler"
                @file-removed="removeHandler"
                @files-added="filesAdded"
                @file-error="errHandler"
                >
                <div class="cube-upload-def clear-fix">
                  <cube-upload-file v-for="(file, i) in files" :file="file" :key="i"/>
                  <cube-upload-btn :multiple="false"/>
                </div>
              </cube-upload>
              <!-- <cube-upload
                :action="action"
                v-model="files"
                :simultaneous-uploads="1"
                @file-success="successHandler"
                @file-removed="removeHandler"
                @files-added="filesAdded"
                @file-error="errHandler"
                /> -->
            </div>
            <van-button @click="submit" :loading="loading" class="submit-btn">确定</van-button>
            <van-popup v-model="dateShow" position="bottom" :overlay="true">
              <van-datetime-picker
                v-model="currentDate"
                type="date"
                :min-date="minDate"
                @confirm="onDoorConfirm"
                @cancel="onDoorCancel"
              />
            </van-popup>
          </div>
        </div>
      </div>
  </sail-page>
</template>

<script>
import { mapState } from "vuex";
import { Toast } from "vant";
import api from "@/api/index.js";

import statusModal from "@/components/statusModal.vue";
import sailPage from "@/components/sail-page.vue";
export default {
  components: {
    sailPage,
    statusModal
  },
  mounted() {
    this.$store.dispatch("repairModule/getMainteTypeTreeInfo").then(treeList => {
      if(treeList) {
        this.cascadePicker = this.$createCascadePicker({
          title: "选择维保类型",
          data: treeList,
          selectedIndex: [0, 0, 0],
          onSelect: this.selectHandle,
          onCancel: this.cancelHandle
        });
      }
    }); // tree
  },
  computed: {
    ...mapState({
      repairForm: state => state.repairModule.repairForm,
      selectedTypeName: state => state.repairModule.selectedTypeName,
      selectedTime: state => state.repairModule.selectedTime,
      files: state => state.repairModule.files
    })
  },
  initData({store, route}) {
    store.commit("repairModule/INIT_REPAIR_FORM");
    store.dispatch("repairModule/initRepairForm");
    let id = route.params.id;
    //
    if(id !== "normal") {
      store.dispatch("repairModule/getDetails", id).then(res => {
        store.commit("repairModule/AGAIN_REPAIR_FORM", res.data.data);
      });
    }
  },
  data: function() {
    return {
      repairId: null,
      showTime: true,
      selectedTypeId: null,
      cascadePicker: null,
      message: "",
      repairCode: null,
      loading: false,
      dateShow: false,
      currentDate: new Date(),
      minDate: new Date(),
      action: {
        target: api.getURL("uploader/upload"),
        data: {
          inputId: "file"
        }
      }
    };
  },
  methods: {
    onRepairTypeClick() {
      this.cascadePicker.show();
    },
    selectHandle(selectedVal, selectedIndex, selectedText) {
      
      this.selectedTypeId = selectedVal[selectedVal.length - 1];
      this.$store.commit("repairModule/CHANGE_TYPE_NAME", selectedText.join("-"));
      //this.selectedTypeName = selectedText.join('-')
      // if(this.selectedTypeName.indexOf('公共区域维保') > -1) {
      //   this.showTime = false
      // }else {
      //   this.showTime = true
      // }
    },
    cancelHandle() {
      
    },
    jumpCallback() {
      this.$router.push({path: `/maintenanceDetail/${this.repairId}`});
    },
    onDoorConfirm(value) {
      //
      this.$store.commit("repairModule/CHANGE_SELECTED_TIME", value.Format("yyyy-MM-dd"));
      //this.selectedTime =  value.Format('yyyy-MM-dd');
      this.$store.commit("repairModule/SET_GO_REPAIR_TIME",  value.Format("yyyy-MM-dd"));
      this.dateShow = false;
    },
    onDoorCancel() {
      this.dateShow = false;
    },
    onDoorClick() {
      this.dateShow = true;
    },
    submit() {
      //
      const reg=11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/;     
      if(!reg.test(this.repairForm.applicantPhone)){
        Toast.fail({
          duration: 1000,
          message: "联系方式格式错误，请重新填写！"
        });
        return false;
      }
      if(!this.repairForm.applicantName) {
        Toast.fail({
          duration: 1000,
          message: "请填写姓名！"
        });
        return false; 
      }
      if(!this.repairForm.applicantPhone ) {
        Toast.fail({
          duration: 1000,
          message: "请填写联系人方式！"
        });
        return false; 
      }
      if(!this.selectedTypeName) {
        Toast.fail({
          duration: 1000,
          message: "请选择维保类型！"
        });
        return false;
      }
      if(!this.selectedTime && this.selectedTypeName.indexOf("室内维保") > -1) {
        Toast.fail({
          duration: 1000,
          message: "请选择上门时间！"
        });
        return false; 
      }
      this.loading = true;
      this.$store.dispatch("repairModule/cLaunchRepair", this.selectedTypeId).then(res => {
        this.loading = false;
        if (res) {
          res.Toast.success({
            duration: 1000,
            message: "申请维保成功"
          });
          this.$store.commit("UPDATE_STATUS_VISIBLE", "maintenance");
          this.repairCode = res.data.data.repairCode;
          this.repairId = res.data.data.id;
          if(!this.repairId) {
            this.repairCode = this.$route.params.code;
            this.repairId = res.data.data;
          }
          //this.$router.back();
        }
      });
      //
    },
    successHandler(file) {
      
      this.$store.commit("repairModule/ADD_IMG_INFO", {
        propCode: "3",
        propName: "维保申请",
        propValue: file.response.data,
        propValueDesc: "维保申请",
        propValueInt: 0,
      });
      ///this.$emit('updateFiles', file, this.imgType, true)
    },
    removeHandler(file) {
      
      this.$store.commit("repairModule/REMOVE_IMG_INFO", file.response.data);
      //this.$emit('updateFiles', file, this.imgType, false)
    },
    errHandler(file) {
      // const msg = file.response.message
      this.$createToast({
        type: "warn",
        txt: "上传失败",
        time: 2000
      }).show();
    },
    filesAdded(files) {
      
      let hasIgnore = false;
      const maxSize = 8 * 1024 * 1024; // 1M
      for (let k in files) {
        const file = files[k];
        if (file.size > maxSize) {
          file.ignore = true;
          hasIgnore = true;
        }
      }
      hasIgnore && Toast.fail("选择的图片过大，无法上传");
    }
  }
};
</script>
<style lang="less">
.has-id {
  .cube-upload-btn {
    display: none;
  }
}
.zero-top .van-hairline--top-bottom::after {
  border-width: 1px 0 0 0;
}
.maintenance-min-part .van-hairline--top-bottom::after {
  border-width: 1px 0 0 0;
}
.spec-placeholder .van-field__control::-webkit-input-placeholder {
  text-align: right;
  color: #808080;
}
.maintenance-apply-wrapper {
  .cube-upload {
    overflow: hidden;
  }
  .clear-fix:after {
    clear: unset;
  }
}
</style>
<style lang="less" scoped>
@nice-desc-gray: #adadad;
.maintenance-apply-wrapper {
  .maintenance-min-part {
    margin-top: 1px;
    background: white;
    padding-top: 19.5px;
    padding-left: 21px;
  }
  .maintenance-part {
    margin-top: 13px;
  }
  .maintenance-desc {
    font-size: 11px;
    margin-top: 11.5px;
    margin-bottom: 11.5px;
    color: @nice-desc-gray;
  }
}
</style>
