<template>
  <div class="app-container">
    <div v-show="isCheck">
      <div class="tab-header webtop">
        <div>{{ viewTitle }}</div>
        <div>
          <el-button type="primary" size="small" @click="handleCreate()">保存</el-button>
          <el-button type="success" size="small" @click="handlePass()">通过</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" label-width="190px" class="formadd" :rules="rules">
          <div class="yancheAdd" style="margin-top: 5px;">
            <el-row class="yancheAdd-bor">
              <el-col :span="12" class="yancheAdd-bor">
                <el-form-item prop="vin" label="车架号：">
                  <el-input
                    v-model="temp.vin"
                    placeholder="请输入车架号"
                    class="addinputw"
                    :readonly="temp.purchaseKey !== '001' && temp.purchaseKey !== '002'"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" class="yancheAdd-bor">
                <el-form-item prop="model" label="车型：">
                  <el-input
                    v-model="temp.model"
                    placeholder="请输入车型"
                    class="addinputw"
                    readonly
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="yancheAdd-bor">
              <el-col :span="24" class="yancheAdd-bor">
                <el-form-item prop="config" label="配置：">
                  <el-input
                    v-model="temp.config"
                    type="textarea"
                    autosize
                    placeholder="请输入配置"
                    class="addinputw addinputw_copy"
                    readonly/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="yancheAdd-bor">
              <el-col :span="24" class="yancheAdd-bor">
                <el-form-item prop="modelDifferenceExplain" label="车型配置差异说明：">
                  <el-input
                    v-model="temp.modelDifferenceExplain"
                    type="textarea"
                    autosize
                    placeholder="请输入车型配置差异说明"
                    class="addinputw addinputw_copy"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item prop="guaranteeCardNo" label="保修卡号：">
                  <el-input
                    v-model="temp.guaranteeCardNo"
                    placeholder="请输入保修卡号"
                    class="addinputw"
                    clearable
                    @keyup.native="temp.guaranteeCardNo = oninput(temp.guaranteeCardNo,2)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item prop="price" label="洗车费：">
                  <el-input
                    v-model="temp.price"
                    placeholder="请输入洗车费"
                    class="addinputw"
                    clearable
                    @keyup.native="temp.price = oninput(temp.price,2)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-button type="primary" size="small" @click="handleChecklist()">验车检查表</el-button>
              </el-col>
            </el-row>
          </div>
          <div class="title">验车相关照片</div>
          <el-row>
            <el-col :span="24">
              <upload ref="uploadImg" v-model="imgList01" :limit="1" bucket="map" :upload-data="{type:'0001'}"></upload>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="3">
              <span>厂家验车单照片</span>
            </el-col>
            <el-col :span="21">
              <upload ref="uploadImg" v-model="imgList02" :limit="1" bucket="map" :upload-data="{type:'0001'}"></upload>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="3">
              <span>验车情况说明</span>
            </el-col>
            <el-col :span="21">
              <el-input
                type="textarea"
                autosize
                placeholder="请输入说明"
                v-model="temp.remarks">
              </el-input>
            </el-col>
          </el-row>
<!--          <el-row class="last_btn">-->
<!--            <el-button type="primary" size="small" @click="handleChecklist()">车辆检查表</el-button>-->
<!--          </el-row>-->
        </el-form>
      </div>
    </div>
    <vehiclechecklist ref="divchecklist" v-show="!isCheck" @doback="resetState"/>
  </div>
</template>

<script>
import { getPathSidByUserSid } from '@/api/cheliang/dictcommons.js'
import { getCarInspectedInfo, saveCarInspectedInfo, submitCarInspectedInfo } from '@/api/supplychain/yancheguanli'
import { getUseOrgByUserSid } from '@/api/cheliang/basevehicle'
import Upload from '@/components/uploadFile/uploadImg.vue'
import vehiclechecklist from '@/views/supplychain/yancheguanli/vehiclechecklist'

export default {
  name: 'yancheguanliAdd',
  components: {
    Upload,
    vehiclechecklist
  },
  data() {
    return {
      viewTitle: '',
      isCheck:true,
      // --按钮菜单-------
      sid: '',
      datas: null,
      stateId: 0,
      FormLoading: false,
      listLoading: false,
      imgList01: [], // 附件上传
      imgList02: [], // 附件上传
      temp: {
        factoryImage: [],
        carInspectedImage: [],
        userSid: window.sessionStorage.getItem('userSid'),
        vin: '',
        config: '',
        model: '',
        inspectedSid: '',
        modelDifferenceExplain:'',
        guaranteeCardNo:''
      }, // 添加和修改
      dialogFormVisible: false, // 添加修改对话框状态
      dialogFormShowVisible: false, // 查看对话框默认关闭状态
      dialogStatus: '', // 对话框状态
      vehiclePhoto: [],
      rules: {
        vin: [{ required: true, message: '车架号不能为空', trigger: 'blur' }], // 车架号
        price: [{ required: true, message: '洗车费不能为空', trigger: 'blur' }] // 洗车费
      }
      // ------------------------------------
    }
  },
  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
    },
    showAdd(row) {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      console.log('点击验车跳转页面',row)
      this.dialogStatus = 'add'
      this.viewTitle = '验车单'
      const data = {
        inspectedSid: row.inspectedSid,
        userSid: window.sessionStorage.getItem('userSid')
      }
      getCarInspectedInfo(data).then((res) => {
        if (res.success) {
          this.temp = res.data
          this.temp.vin = res.data.vin
          this.temp.config = res.data.config
          this.temp.model = res.data.model
          this.temp.inspectedSid = res.data.inspectedSid
          this.temp.purchaseKey = res.data.purchaseKey // 只有是排产的时候才可编辑
          if (this.temp.carInspectedImage.length > 0) {
            for (var i = 0; i < this.temp.carInspectedImage.length; i++) {
              const imgName = this.temp.carInspectedImage[i].split('/')
              this.imgList01.push({
                name: imgName[imgName.length - 1],
                url: this.temp.carInspectedImage[i]
              })
            }
            console.log('imgList01', this.imgList01)
          }
          if (this.temp.factoryImage.length > 0) {
            for (var i = 0; i < this.temp.factoryImage.length; i++) {
              const imgName = this.temp.factoryImage[i].split('/')
              this.imgList02.push({
                name: imgName[imgName.length - 1],
                url: this.temp.factoryImage[i]
              })
            }
            console.log('imgList02', this.imgList02)
          }
        }
      })
    },
    // showEdit(sid) {
    //   this.$nextTick(() => {
    //     this.$refs['dataForm'].clearValidate()
    //   })
    //   this.dialogStatus = 'update'
    //   this.viewTitle = '【修改】车辆台账'
    //   this.temp.sid = sid
    //   console.log('修改页面sid', this.temp.sid)
    //   getCarInspected(sid).then((response) => {
    //     if (response.code === '200') {
    //       if (response.data.createOrg) {
    //         console.log('级联选择1：', response.data.useOrg)
    //         this.useOrgArry = response.data.createOrg
    //         console.log('级联选择2：', this.useOrgArry)
    //       }
    //       this.temp = response.data
    //       this.getLocation()
    //       this.getModelConfig(this.temp.modelSid)
    //     }
    //   })
    //   this.getType()
    //   this.getZuZhi()
    //   this.getUseOrg()
    // },
    handleChecklist(){
      this.isCheck = false
      this.$refs['divchecklist'].showCheck(this.temp.inspectedSid)
    },
    resetState(){
      this.isCheck = true
    },
    // 获得使用组织
    getUseOrg() {
      const userSid = window.sessionStorage.getItem('userSid')
      getUseOrgByUserSid({ userSid: userSid }).then((res) => {
        if (res.success) {
          this.temp.useOrgName = res.data.name
          this.temp.useOrg = res.data.sid
          this.temp.createOrg = res.data.sid
          this.temp.createOrgName = res.data.name
          this.org_list = res.data
        }
      })
    },
    getPathSid() {
      const userSid = window.sessionStorage.getItem('userSid')
      getPathSidByUserSid({ userSid: userSid }).then((res) => {
        if (res.code === '200') {
          this.listQuery.params.createOrgSId = res.data
          this.useOrg = res.data
        }
      })
    },
    getUrl() {
      if (this.imgList01.length > 0) {
        console.log('imgList01', this.imgList01)
        const img01_list = []
        for (var i = 0; i < this.imgList01.length; i++) {
          img01_list.push(this.imgList01[i].url)
          this.temp.carInspectedImage = img01_list
        }
      } else {
        this.temp.carInspectedImage = []
      }
      if (this.imgList02.length > 0) {
        console.log('imgList02', this.imgList02)
        const img02_list = []
        for (var i = 0; i < this.imgList02.length; i++) {
          img02_list.push(this.imgList02[i].url)
          this.temp.factoryImage = img02_list
        }
      } else {
        this.temp.factoryImage = []
      }
    },
    // ----------------------------------方法--------------------
    // 返回
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.temp = {
        factoryImage: [],
        carInspectedImage: [],
        userSid: window.sessionStorage.getItem('userSid'),
        vin: '',
        config: '',
        model: '',
        inspectedSid: '',
        modelDifferenceExplain:'',
        guaranteeCardNo:''
      }
      this.imgList01 = []
      this.imgList02 = []
      this.$emit('doback')
    },
    // 提交添加数据
    handleCreate() {
      this.getUrl()
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.FormLoading = true
          if (this.temp.carInspectedImage.length == 0) {
            this.$message({
              showClose: true,
              message: '请上传验车相关照片！',
              type: 'error'
            });
            return
          }
          if (this.temp.factoryImage.length == 0) {
            this.$message({
              showClose: true,
              message: '请上传厂家验车单照片！',
              type: 'error'
            });
            return
          }
          // 只需添加和修改
          saveCarInspectedInfo(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'
              // });
            }
          })
        }
      })
    },
    handlePass() {
      this.getUrl()
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          submitCarInspectedInfo(this.temp).then((response) => {
            this.FormLoading = false
            if (this.temp.carInspectedImage.length == 0) {
            this.$message({
              showClose: true,
              message: '请上传验车相关照片！',
              type: 'error'
            });
            return
          }
          console.log('照片02',this.temp.factoryImage)
          if (this.temp.factoryImage.length == 0) {
            this.$message({
              showClose: true,
              message: '请上传厂家验车单照片！',
              type: 'error'
            });
            return
          }
            if (response.code === '200') {
              this.dialogFormVisible = false
              this.handleReturn('true')
            } else {
              this.$message({
                showClose: true,
                message: '操作失败！',
                type: 'error'
              })
            }
          })
        }
      })
    }

    // 处理图片
    // this.temp.vehiclePhoto = []
    // if (this.vehiclePhoto_Images.length > 0) {
    //   for (var i = 0; i < this.vehiclePhoto_Images.length; i++) {
    //     var image_start = this.vehiclePhoto_Images.indexOf('/upload') + 8
    //     var image_url = this.vehiclePhoto_Images.substring(image_start)
    //     this.temp.vehiclePhoto.push(image_url)
    //   }
    // }
  }
}
</script>

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

.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;
}
.addinputw_copy{
  width: 92% !important;
}
.formadd .last_btn{
  float: right;
  top: 30px;
}
</style>
