<template>
  <div class="app-container">
    <div class="tab-header webtop">
      <div>{{ viewTitle }}</div>
      <div>
        <el-button type="primary" size="small" @click="handleCreate()">保存</el-button>
        <el-button type="primary" size="small" @click="handleSubmit()">提交</el-button>
        <el-button type="info" size="small" @click="handleReturn()">返回</el-button>
      </div>
    </div>
    <div class="listconadd">
      <div class="titwu">车辆存放地点变更申请</div>
      <el-form ref="dataForm" :model="temp" label-position="right" class="formadd" :rules="rules">
        <el-row style="border-top: 1px solid #e0e3eb;">
          <el-col :span="3">
            <span>申请日期</span>
          </el-col>
          <el-col :span="9">
            <el-form-item>
              <span>{{ temp.applicantDate }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <span>申请人</span>
          </el-col>
          <el-col :span="9">
            <el-form-item>
              <span>{{ temp.applicantName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3">
            <span>现存放地点</span>
          </el-col>
          <el-col :span="9">
            <el-form-item prop="location">
              <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-form-item>
          </el-col>
          <el-col :span="3">
            <span>目标存放地点</span>
          </el-col>
          <el-col :span="9">
            <el-form-item prop="targetLocation">
              <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-form-item>
          </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 class="icon">*</span>车架号</span>
          </el-col>
          <el-col :span="21">
            <el-form-item prop="vinNo">
              <span>{{ temp.vinNo }}</span>
              <el-button size="small" type="primary" @click="selectVinNo" class="selectVinNoBtn">选择</el-button>
              <!--              <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-form-item>
          </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
                      @keyup.native="temp.applicantFunds = oninput(temp.applicantFunds,2)"/>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3"> <!--<span class="icon">*</span>-->
            <span>移库操作人</span>
          </el-col>
          <el-col :span="9">
            <el-form-item prop="operator">
              <el-input v-model="temp.operator" maxlength="125" placeholder="" class="addinputw" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <span>保险状态</span>
          </el-col>
          <el-col :span="9">
            <el-form-item prop="InsuranceStateKey">
              <el-radio v-model="temp.InsuranceStateKey" label="0">否</el-radio>
              <el-radio v-model="temp.InsuranceStateKey" label="1">是</el-radio>
            </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>
    <!-- ======== 打开选择车架号 ======== -->
    <el-dialog :showClose="false" :visible.sync="vinNoVisible">
      <div slot="title">
        <span>选择车架号</span>
        <div class="vinNoBtn">
          <el-button type="primary" @click="selectionvinNo()">确 定</el-button>
          <el-button @click="vinNoVisible = false">取 消</el-button>
        </div>
      </div>
      <div>
        <el-form ref="multipleTable" :inline="true" :model="vinNoList" class="vinNoForm" label-width="100px">
          <el-col :span="14">
            <el-form-item label="车架号:">
              <el-input v-model="vinNoList.params.vin" clearable class="addinputw" placeholder="车架号"/>
            </el-form-item>
          </el-col>
          <el-col :span="10" class="dialogBtn">
            <el-button type="primary" size="small" @click="handlevinNo">查询</el-button>
          </el-col>
        </el-form>
      </div>
      <el-table :key="tableKey" v-loading="vinNoLoading" :data="listvinNo" border fit highlight-current-row
                style="width: 100%;" @selection-change="handleSelectionvinNo">
        <el-table-column align="center" type="selection" width="50"/>
        <el-table-column :index="vinNoindexMethod" align="center" label="序号" type="index" width="80"/>
        <el-table-column align="center" label="车架号" prop="billNo">
          <template slot-scope="scope">
            <span>{{ scope.row.vin }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pages">
        <div class="tit"/>
        <!-- 翻页 -->
        <pagination
          v-show="vinNototal > 0"
          :limit.sync="vinNoList.size"
          :page.sync="vinNoList.current"
          :total="vinNototal" class="pagination" @pagination="getvinNoList"/>
      </div>
    </el-dialog>
  </div>
</template>

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

export default {
  name: 'cunfangdidianbiangengAdd',
  components: {
    Upload
  },
  data() {
    return {
      viewTitle: '',
      // --按钮菜单-------
      sid: '',
      datas: null,
      stateId: 0,
      FormLoading: false,
      listLoading: false,
      location_list: [],
      targetLocation_list: [],
      imgList: [], // 附件上传
      vinNo_list: [], // 车架号
      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: []
      }, // 添加和修改
      dialogFormVisible: false, // 添加修改对话框状态
      dialogFormShowVisible: false, // 查看对话框默认关闭状态
      dialogStatus: '', // 对话框状态
      vehiclePhoto: [],
      // 现车车架号列表
      vinNoVisible: false,
      tableKey: 0,
      vinNototal: 1,
      vinNoLoading: false,
      vinNoCount: 0,
      vinNoChoice: [],
      listvinNo: [],
      vinNoList: {
        current: 1,
        size: 20,
        params: {
          vin: '',
          warehouseSid: '',
          userSid: window.sessionStorage.getItem('userSid')
        }
      },
      rules: {
        vinNo: [{ required: true, message: '车架号不能为空', trigger: 'change' }],
        operator: [{ required: true, message: '经办人不能为空', trigger: 'change' }],
        InsuranceStateKey: [{ required: true, message: '保险状态不能为空', trigger: 'blur' }],
        location: [{ required: true, message: '现存放地点不能为空', trigger: 'change' }],
        targetLocation: [{ required: true, message: '目标存放地点不能为空', trigger: 'change' }]
      }
      // ------------------------------------
    }
  },
  methods: {
    // 输入数字正则
    oninput(val, limit = 0) {
      val = val.replace(/[^\d.]/g, '') //保留数字
      val = val.replace(/^00/, '0.') //开头不能有两个0
      val = val.replace(/^\./g, '0.') //开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') //两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); //只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' //两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    },
    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
          this.listvinNo = 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.vinNoList.params.warehouseSid = this.temp.locationSid
      // 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)
    },
    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) {
      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.instanceId = res.data.procInstId
          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()
    },
    // ------------ 选择车架号的方法 ------------
    // 点击选择车架号
    selectVinNo() {
      if (this.temp.locationSid !== '') {
        this.vinNoVisible = true
        this.$nextTick(() => {
          this.handlevinNo()
        })
      } else {
        this.$message({
          showClose: true,
          message: '请选择现存放地点！',
          type: 'error'
        })
      }
    },
    // 查询
    handlevinNo() {
      this.vinNoList.current = 1
      this.getvinNoList()
    },
    // 请求车架号列表接口
    getvinNoList() {
      const _this = this
      this.vinNoLoading = true
      getVinByWarehouseSid(this.vinNoList)
        .then(resp => {
          _this.vinNoLoading = false
          const data = resp.data
          _this.vinNototal = data.total
          _this.listvinNo = data.records
        })
        .catch(() => {
          _this.vinNoLoading = false
        })
    },
    // 勾选数据
    handleSelectionvinNo(row) {
      this.vinNoChoice = row
      if (this.vinNoChoice.length > 1){
        this.$message({
          showClose: true,
          message: '仅可选择一个车架号！',
          type: 'error'
        });
        return
      }
    },
    // 确认选择车架号
    selectionvinNo() {
      this.temp.vinNo = this.vinNoChoice[0].vin
      this.vinNoVisible = false
      // this.$refs.multipleTable.clearSelection();
    },

    // 现车序号
    vinNoindexMethod(index) {
      var pagestart = (this.vinNoList.current - 1) * this.vinNoList.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    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: []
      }
      this.imgList = []
      this.vinNo_list = []
      this.$emit('doback')
    },
    // 提交添加数据
    handleCreate() {
      if (this.temp.InsuranceStateKey == '0') {
        this.temp.InsuranceState = '否'
        this.temp.policyImage = []
        this.imgList = []
      }
      if (this.temp.InsuranceStateKey == '1') {
        this.temp.InsuranceState = '是'
      }
      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
              this.handleReturn('true')
            } else {
              this.$message({
                showClose: true,
                message: '保存失败！',
                type: 'error'
              })
            }
          })
        }
      })
    },
    handleSubmit() {
      const _this = this
      if (this.temp.InsuranceStateKey == '0') {
        this.temp.InsuranceState = '否'
        this.temp.policyImage = []
        this.imgList = []
      }
      if (this.temp.InsuranceStateKey == '1') {
        this.temp.InsuranceState = '是'
      }
      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) {
                _this.handleReturn('true')
              }
            }).catch(() => {
              // this.submitdisabled = false
            })
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

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

.listconadd {
  width: 100%;
  padding: 0 240px !important;
}

.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;
}

.selectVinNoBtn {
  display: inline-block;
  position: absolute;
  top: 5px;
  right: 5px;
}

.vinNoBtn {
  float: right;
}

.vinNoForm {
  text-align: center;
}
</style>
