<template>
  <div class="app-container">
    <div class="tab-header webtop">
      <div>{{ viewTitle }}</div>
      <div>
        <el-button type="primary" size="small" :disabled="disabled" @click="handleCreate()">保存</el-button>
        <el-button type="primary" size="small" :disabled="disabled" @click="handleSubmit()">提交</el-button>
      </div>
    </div>
    <div class="">
      <div class="title">车辆存放地点变更申请</div>
      <el-form ref="dataForm" :model="temp" label-position="right" class="formadd" :rules="rules">
        <div class="tit">
          <div class="times">
            <div>
              <span>申请日期：</span>
              <span>{{ temp.applicantDate }}</span>
            </div>
            <div>
              <span>申请人：</span>
              <span>{{ temp.applicantName }}</span>
            </div>
          </div>
        </div>
        <el-row style="border-top: 1px solid #e0e3eb;">
          <el-col :span="3">
            <span>现存放地点</span>
          </el-col>
          <el-col :span="9">
            <el-select v-model="temp.location" placeholder="请选择" clearable class="addinputw"
                       @change="locationChange">
              <el-option v-for="item in warehouwarehouse_list" :key="item.dictKey" :label="item.dictValue"
                         :value="item.dictValue"/>
            </el-select>
          </el-col>
          <el-col :span="3">
            <span>目标存放地点</span>
          </el-col>
          <el-col :span="9">
            <el-select v-model="temp.targetLocation" placeholder="请选择" clearable class="addinputw"
                       @change="targetLocationChange">
              <el-option v-for="item in warehouwarehouse_list" :key="item.dictKey" :label="item.dictValue"
                         :value="item.dictValue"/>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3">
            <span>车架号</span>
          </el-col>
          <el-col :span="21">
            <el-select v-model="temp.vinNo" placeholder="请选择" filterable clearable class="addinputw">
              <el-option v-for="item in vinNo_list" :key="item.vin" :label="item.vin" :value="item.vin"/>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3">
            <span>变更原因</span>
          </el-col>
          <el-col :span="21">
            <el-input v-model="temp.changeReason" maxlength="125" placeholder="" class="addinputw" clearable/>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3">
            <span>申请费用</span>
          </el-col>
          <el-col :span="21">
            <el-input v-model="temp.applicantFunds" maxlength="125" placeholder="" class="addinputw" clearable/>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3"> <!--<span class="icon">*</span>-->
            <span>经办人</span>
          </el-col>
          <el-col :span="9">
            <el-input v-model="temp.operator" maxlength="125" placeholder="" class="addinputw" clearable/>
          </el-col>
          <el-col :span="3">
            <span>保险状态</span>
          </el-col>
          <el-col :span="9">
            <el-form-item>
              <el-radio-group v-model="temp.InsuranceStateKey">
                <el-radio v-for="item in InsuranceState_list" :key="item.key" :label="item.key"
                          @change="InsuranceStateChange(item.key)">{{ item.value }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="temp.InsuranceStateKey == '1'">
          <el-col :span="3">
            <span>保单</span>
          </el-col>
          <el-col :span="21">
            <upload ref="uploadImg" v-model="imgList" :limit="1" bucket="map" :upload-data="{type:'0001'}"/>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3">
            <span>临牌</span>
          </el-col>
          <el-col :span="21">
            <el-input v-model="temp.temporaryCard" maxlength="125" placeholder="" class="addinputw" clearable/>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  getCarTransferInfo,
  getVinByWarehouseSid,
  saveCarTransferInfo,
  selectWarehouseByUserSid,
  submitCarTransfer
} from '@/api/supplychain/cunfangdidianbiangeng'
import Upload from '@/components/uploadFile/uploadImg.vue'

export default {
  name: 'cunfangdidianbiangengEdit',
  components: {
    Upload
  },
  data() {
    return {
      viewTitle: '',
      // --按钮菜单-------
      sid: '',
      datas: null,
      stateId: 0,
      FormLoading: false,
      listLoading: false,
      disabled: false,
      location_list: [],
      targetLocation_list: [],
      imgList: [], // 附件上传
      vinNo_list: [], // 车架号
      InsuranceState_list: [{
        key: '0',
        value: '否'
      }, {
        key: '1',
        value: '是'
      }],
      warehouwarehouse_list: [], // 存放地点
      temp: {
        sid: '',
        // taskId: '',
        // procInsId: '',
        userSid: window.sessionStorage.getItem('userSid'),
        // applyId: '',
        applicantName: '',
        applicantDate: '',
        location: '',
        locationKey: '',
        locationSid: '',
        vinNo: '',
        targetLocation: '',
        targetLocationKey: '',
        targetLocationSid: '',
        changeReason: '',
        applicantFunds: '',
        operator: '',
        InsuranceState: '',
        InsuranceStateKey: '',
        temporaryCard: '',
        policyImage: [],
        instanceId:'',
        taskId:'',
      }, // 添加和修改
      dialogFormVisible: false, // 添加修改对话框状态
      dialogFormShowVisible: false, // 查看对话框默认关闭状态
      dialogStatus: '', // 对话框状态
      vehiclePhoto: [],
      rules: {}
      // ------------------------------------
    }
  },
  mounted() {
    window.parent.postMessage({
      cmd: 'returnHeight',
      params: {
        // 告诉父级页面，子页面的弹框高度。
        code: 2,
        data: document.body.scrollHeight + 'px'
      }
    }, '*')
  },
  created() {
    console.log('url:' + window.location.href)
    var a = window.location.href.indexOf('?') + 1 // 第一个?后面的一个字符的位置
    var b = window.location.href.indexOf('#data') // 第一个#data出现的位置
    const info = window.location.href.slice(a, b)
    var sid = info.substr(info.indexOf('=') + 1)
    // ===获取参数
    var one = window.location.href.lastIndexOf('#') + 1
    var two = window.location.href.lastIndexOf('}') + 1
    const data = decodeURI(window.location.href.slice(one, two)) // url解码unescape()已从web中移除,尽量不使用
    var tar = data.substr(data.indexOf('=') + 1)
    const obj = JSON.parse(tar)
    console.log('iframe页面获取的obj:', obj)
    this.showEdit(sid,obj.instanceId,obj.taskId)
  },
  methods: {
    getType() {
      // 存放地点
      const userSid = window.sessionStorage.getItem('userSid')
      selectWarehouseByUserSid(userSid).then((res) => {
        if (res.code === '200') {
          this.warehouwarehouse_list = res.data
          console.log('存放地点', this.warehouwarehouse_list)
        }
      })
    },
    getVin(sid) {
      const data = {
        warehouseSid: sid,
        userSid: window.sessionStorage.getItem('userSid')
      }
      getVinByWarehouseSid(data).then((res) => {
        if (res.code === '200') {
          this.vinNo_list = res.data
          console.log('车架号', this.vinNo_list)
        }
      })
    },
    locationChange(val) {
      const choosetItem = this.warehouwarehouse_list.filter((item) => item.dictValue == val)
      this.temp.locationKey = choosetItem[0].dictKey
      this.temp.locationSid = choosetItem[0].sid
      this.getVin(this.temp.locationSid)
      console.log('name:', this.temp.location, 'key:', this.temp.locationKey, 'sid:', this.temp.locationSid)
    },
    targetLocationChange(val) {
      const choosetItem = this.warehouwarehouse_list.filter((item) => item.dictValue == val)
      this.temp.targetLocationKey = choosetItem[0].dictKey
      this.temp.targetLocationSid = choosetItem[0].sid
      console.log('name:', this.temp.targetLocation, 'key:', this.temp.targetLocationKey, 'sid:', this.temp.targetLocationSid)
    },
    InsuranceStateChange(val) {
      const choosetItem = this.InsuranceState_list.filter((item) => item.key == val)
      this.temp.InsuranceState = choosetItem[0].value
      console.log('name:', this.temp.InsuranceState, 'key:', this.temp.InsuranceStateKey)
    },
    showAdd() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.dialogStatus = 'add'
      this.viewTitle = '【新增】车辆存放地点变更申请'
      this.temp.applicantName = window.sessionStorage.getItem('name')
      var nowDate = new Date()
      var date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        day: nowDate.getDate()
      }
      var dayDate = date.year + '-' + (date.month >= 10 ? date.month : '0' + date.month) + '-' + (date.day >= 10 ? date.day : '0' + date.day)
      this.temp.applicantDate = dayDate
      this.getType()
    },
    showEdit(sid, instanceId, taskId) {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.dialogStatus = 'update'
      this.viewTitle = '【修改】车辆存放地点变更申请'
      this.temp.sid = sid
      const data = {
        userSid: window.sessionStorage.getItem('userSid'),
        sid: sid
      }
      getCarTransferInfo(data).then((res) => {
        if (res.success) {
          this.temp = res.data
          this.temp.InsuranceStateKey = res.data.insuranceStateKey
          this.temp.InsuranceState = res.data.insuranceState
          this.temp.instanceId = instanceId
          this.temp.taskId = taskId
          if (this.temp.policyImage.length > 0) {
            for (var i = 0; i < this.temp.policyImage.length; i++) {
              const imgName = this.temp.policyImage[i].split('/')
              this.imgList.push({
                name: imgName[imgName.length - 1],
                url: this.temp.policyImage[i]
              })
            }
          }
        }
      })
      this.getType()
    },
    getUrl() {
      if (this.temp.InsuranceStateKey == '1') {
        if (this.imgList.length > 0) {
          console.log('保存imgList', this.imgList)
          const img_list = []
          for (var i = 0; i < this.imgList.length; i++) {
            img_list.push(this.imgList[i].url)
            this.temp.policyImage = img_list
            console.log('保存img_list', img_list)
          }
        } else {
          this.temp.policyImage = []
        }
      } else {
        this.temp.policyImage = []
      }
    },
    // ----------------------------------方法--------------------
    // 返回
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.temp = {
        sid: '',
        // taskId: '',
        // procInsId: '',
        userSid: window.sessionStorage.getItem('userSid'),
        // applyId: '',
        applicantName: '',
        applicantDate: '',
        location: '',
        locationKey: '',
        locationSid: '',
        vinNo: '',
        targetLocation: '',
        targetLocationKey: '',
        targetLocationSid: '',
        changeReason: '',
        applicantFunds: '',
        operator: '',
        InsuranceState: '',
        InsuranceStateKey: '',
        temporaryCard: '',
        policyImage: [],
        instanceId:'',
        taskId:''
      }
      this.imgList = []
      this.vinNo_list = []
      this.$emit('doback')
    },
    // 提交添加数据
    handleCreate() {
      this.getUrl()
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.FormLoading = true
          // 只需添加和修改
          saveCarTransferInfo(this.temp).then((response) => {
            this.FormLoading = false
            if (response.code === '200') {
              this.dialogFormVisible = false
              window.parent.postMessage({
                cmd: 'returnHeight',
                params: {
                  // 操作成功，告诉父级页面关闭弹框
                  code: 1
                }
              }, '*')
            } else {
              this.$message({
                showClose: true,
                message: '保存失败！',
                type: 'error'
              })
            }
          })
        }
      })
    },
    handleSubmit() {
      const _this = this
      this.getUrl()
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          // this.submitdisabled = true
          this.$confirm('是否确定提交该业务', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            submitCarTransfer(this.temp).then(resp => {
              // this.submitdisabled = false
              if (resp.success) {
                window.parent.postMessage({
                  cmd: 'returnHeight',
                  params: {
                    // 操作成功，告诉父级页面关闭弹框
                    code: 1
                  }
                }, '*')
              }
            }).catch(() => {
              // this.submitdisabled = false
            })
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
/deep/ .el-autocomplete {
  width: 80%;
}

.title {
  padding-top: 28px;
}

.formadd .title {
  padding: 10px !important;
}

.yancheAdd .el-row {
  border: 0 !important;
}

.yancheAdd .el-col {
  border: 0 !important;
}

/deep/ .el-col-3 {
  text-align: right;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px !important;
  font-weight: 600;
}

.tit {
  margin-bottom: 30px;
  border-bottom: 1px solid #e0e3eb;
}

.times {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 30px 0 10px 0;
  margin: 0 auto 0 auto;
  width: 75%;
  font-size: 14px;
  text-align: center;
}
.title{
  text-align: center;
}
</style>
