美文网首页
vue3 watch

vue3 watch

作者: 糖醋里脊120625 | 来源:发表于2023-08-29 10:34 被阅读0次

<template>
  <div class="basic-box">

    <BasicForm ref="FormInfo" @eventIsObject="receiveChildObject"></BasicForm>
    <!-- 商品信息 -->

    <div class="registration_namebox_between">
      <div class="registration_left_name">基本信息</div>
    </div>
    <van-field
      required
      label="入场日期"
      name="datetimePicker"
      v-model="regEntryDate"
      is-link
      readonly
      @click="ShowentryTime = true"
    />

    <van-field
      required
      v-model="licensePlateNo"
      label="车牌号"
      placeholder="请输入车牌号"
    >
      <template #button>
        <van-button size="mini" @click="selectCarCode()" icon="arrow" />
      </template>
    </van-field>

    <van-field name="radio" required label="车辆类型">
      <template #input>
        <van-radio-group v-model="carType" direction="horizontal">
          <van-radio name="SELF_PROVIDE">自备车</van-radio>
          <van-radio name="LOGISTICS">物流车</van-radio>
        </van-radio-group>
      </template>
    </van-field>

    <van-field
      required
      v-model="productOrigin"
      is-link
      readonly
      name="picker"
      label="货源地"
      placeholder="请选择货源地"
      @click="selectArea()"
    />
    <div class="ground-span"></div>
    <div class="registration_namebox_between">
      <div class="registration_left_name">供应商信息</div>
    </div>
    <van-field name="radio" required label="供应商类型">
      <template #input>
        <van-radio-group v-model="supplyType" direction="horizontal" @change="changesupply">
          <van-radio name="1">供应商供货</van-radio>
          <van-radio name="2">个体户</van-radio>
        </van-radio-group>
      </template>
    </van-field>


    <van-field 
      required 
      v-model="supplierName" 
      readonly 
      @click-input="selectSupply()" 
      :label="nameType" 
      :placeholder="nameType"
      right-icon="arrow"
    >
    
    </van-field>

    <van-field
      v-if="supplyType == '1'"
      v-model="supplierCreditCode"
      readonly
      center
      required
      label="营业执照号"
      placeholder="请输入营业执照号"
    >
      <!-- <template #button>
        <van-button
        icon="search"
        plain 
        size="small"
        :loading="loading"
        @click="examine"
        type="primary"
        ></van-button
        >
      </template> -->
    </van-field>

    <!-- <van-field
      v-if="supplyType == '1'"
      readonly
      v-model="supplierName"
      required
      name="picker"
      label="供应商"
      placeholder="请选择供应商"
    >
    </van-field> -->

    <van-field
     v-if="supplyType == '2'"
      readonly
      required
      label="身份证号"
      v-model="supplierContactIdCard"
      placeholder="请填写身份证号"
    >
      <!-- <template #button>
        <van-button size="mini" @click="selectIdCard()" icon="arrow-down" />
      </template> -->
    </van-field>

    <van-field
      required
      readonly
      :label="labelName"
      v-model="supplierContactName"
      placeholder="请输入联系人"
    />
 
    <van-field
      required
      :label="labelPhone"
      readonly
      v-model="supplierContactMobileNo"
      placeholder="请输入手机号"
    >
    </van-field>




    <!-- 车牌弹出 -->
    <van-popup v-model:show="showCarCode" position="bottom">
      <van-picker
        :columns="carData"
        value-key="licensePlateNo"
        @confirm="CarConfirm"
        @cancel="showCarCode = false"
      />
    </van-popup>
    <!-- 入场时间弹出 -->
    <van-popup v-model:show="ShowentryTime" position="bottom">
      <van-datetime-picker
        :min-date="minDate"
        v-model="currentDate"
        type="datetime"
        @confirm="entryTimeConfirm"
        @cancel="ShowentryTime = false"
        :formatter="formatter"
        :filter="filter"
      />
    </van-popup>

    <!-- 货源地弹出 -->
    <van-popup v-model:show="showArea" round position="bottom">
      <van-cascader
        v-model="cascaderValue"
        title=""
        :options="newAreaData"
        @close="showArea = false"
        @finish="onFinish"
        :field-names="fieldNames"
      />
    </van-popup>
    <!-- 身份证弹出 -->
    <van-popup v-model:show="IDCardShow" position="bottom">
      <van-picker
        :columns="IDCardData"
        value-key="contactName"
        @confirm="IDCardConfirm"
        @cancel="IDCardShow = false"
      />
    </van-popup>

    <!-- 供应商弹出 -->
    <van-popup v-model:show="supplierShow" position="bottom">
      <van-picker
        :columns="supplyData"
        value-key="name"
        @confirm="supplyConfirm"
        @cancel="supplierShow = false"
      />

      <div class="add-supply" @click="addSupply">新增</div>
      
    </van-popup>
  </div>
</template>
  
  <script setup>
import dayjs from "dayjs";
import bus from "../util/bus"
import { usefulCars } from "@/request/carApi.js";
import { list, dangerousArea } from "@/request/supplyApi.js";
import { verifyAgainstCreditCode } from "@/request/merchantsApi.js";

import BasicForm from "@/components/BasicForm.vue";
import { Toast } from "vant";
import { useRouter, } from 'vue-router' 
import { onMounted, onBeforeUnmount, ref, defineExpose,watch,defineEmits } from "vue";
import store from '@/store'

const labelName =ref("供应商联系人")
const labelPhone = ref("供应商手机号")
const nameType = ref("供应商名称")


const FormInfo = ref();

const router = useRouter();
const showCarCode = ref(false);
const ShowentryTime = ref(false);
const regEntryDate = ref("");
const enterTel = ref("");
const licensePlateNo = ref("");
const enterCarID = ref("");
const currentDate = ref(new Date());
const enterName = ref("");
const minDate = ref(new Date());
const carData = ref([]);

const showArea = ref(false);
const productOrigin = ref("");

const supplyType = ref('1');

const supplierShow = ref(false);
const supplyData = ref([]);

const carType = ref("");

const IDCardShow = ref(false)
const IDCardData = ref([])

const supplierCreditCode = ref(""); //社会信用码
const supplierName = ref(""); //供应商名称
const supplierContactName = ref(""); //供应商姓名
const supplierContactMobileNo = ref(""); //供应商联系方式
const supplierContactIdCard = ref(""); //身份证号

const originProvinceCode = ref("");
const originProvinceName = ref("");
const originCityCode = ref("");
const originCityName = ref("");
const originDistrictCode = ref("");
const originDistrictName = ref("");
const loading = ref(false);
const newAreaData = ref([]);
const fieldNames = {
  text: "name",
  value: "code",
  children: "items",
};
const emit = defineEmits(['ListenTimeArea'])

watch(() => [regEntryDate.value, productOrigin.value ,licensePlateNo.value], (newVal, oldVal) => {
    emit('ListenTimeArea',newVal)
  },
  {
    deep:true,
    immediate:true,
})




//开始
onMounted(() => {
  document.querySelector('body').setAttribute('style', 'overflow:auto;')
  

  getAllCars();
  enterName.value = JSON.parse(sessionStorage.getItem("storageSubject")).merchantInfo.contactName;
  enterTel.value = JSON.parse(sessionStorage.getItem("storageSubject")).merchantInfo.contactMobileNo;
});
const formatter = (type, val) => {
  if (type === 'year') {
    return `${val}年`;
  }
  if (type === 'month') {
    return `${val}月`;
  }
  if (type === 'day') {
    return `${val}日`;
  }
  if (type === 'hour') {
    return `${val}时`;
  }
  if (type === 'minute') {
    return `${val}分`;
  }
  return val;
};
const filter = (type, options) => {
  if (type === "minute") {
    return options.filter((option) => Number(option) % 30 === 0);
  }
  return options;
};



function examine() {
  // creditCode.value "91320508MA1TECY43L"
  if(supplierCreditCode.value ==''){
    Toast.fail("社会信用代码不可为空");
    return
  }
  loading.value = true;
  verifyAgainstCreditCode(supplierCreditCode.value)
    .then((res) => {
      if (res) {
        Toast.success("验证成功");
        supplierName.value = res.data.unitName;
      }
    })
    .catch((error) => {
      console.log(error);
    })
    .finally((end) => {
      loading.value = false;
    });
}

// 货源地确认事件

const onFinish = ({ selectedOptions }) => {
  originProvinceCode.value = selectedOptions[0].code;
  originProvinceName.value = selectedOptions[0].name;
  originCityCode.value = selectedOptions[1].code;
  originCityName.value = selectedOptions[1].name;
  originDistrictCode.value = selectedOptions[2].code;
  originDistrictName.value = selectedOptions[2].name;

  productOrigin.value = selectedOptions
  .filter((item) => !!item)
  .map((item) => item.name)
  .join("/");
  showArea.value = false;
};


function getAllCars() {
  usefulCars().then((res) => {
    carData.value = res.data;
  })
  .catch((error) => {
    console.log(error);
  });
}

function selectArea() {
  limitArea();
  showArea.value = true;
}

function limitArea() {
  dangerousArea()
    .then((res) => {
      let provincesFloor = res.data.provinces.map((item) => {
        let cityFloor = item.cities.map((each) => {
          let countyFloor = each.districts.map((every) => {
            return {
              name: every.name,
              code: every.code,
              riskLevel: every.riskLevel,
              disabled: every.riskLevel == "HIGH" || every.riskLevel == "MID" ? true : false,
            };
          });
          return {
            name: each.name,
            code: each.code,
            items: countyFloor,
          };
        });
        return {
          name: item.name,
          code: item.code,
          items: cityFloor,
        };
      });
      newAreaData.value = provincesFloor;

      //  console.log(newArea)
      // newAreaData.value = newArea
    })
    .catch((error) => {
      console.log(error);
    });
}

function IDCardConfirm(selectVal){
  const newdata = JSON.parse(JSON.stringify(selectVal));
  supplierContactIdCard.value = newdata.contactIdCard;
  supplierContactName.value = newdata.contactName;
  supplierContactMobileNo.value = newdata.contactMobileNo;
  IDCardShow.value =false;
}





function OpenSupply(){

}
function selectIdCard(){
  const params = {
    page: 1,
    pageSize: 999,
    hasCreditCode:false
  };
  list(params)
  .then((res) => {
    IDCardData.value = res.data.list;
  })
  .catch((error) => {
    console.log(error);
  });
  IDCardShow.value =true;
}



// 获取所有供应商
// hasCreditCode:true
function selectSupply() {
  supplierShow.value = true;
  let judgeCreditCode = supplyType.value=="1"?true:false
  const params = {
    page: 1,
    pageSize: 999,
    hasCreditCode:judgeCreditCode
  };
  list(params)
  .then((res) => {
    supplyData.value = res.data.list;
  })
  .catch((error) => {
    console.log(error);
  });
}


function receiveChildObject(newdata) {
  if(newdata!= null){
      supplierContactName.value = newdata.contactName;
      supplierContactMobileNo.value = newdata.contactMobileNo;
      supplierName.value = newdata.name;
      supplierCreditCode.value = newdata.creditCode;
      supplierShow.value = false;
      supplierContactIdCard.value = newdata.contactIdCard;
  }
  document.querySelector('body').setAttribute('style', 'overflow:auto;')
  
}


// ddddddddddddddd
function addSupply(){
  document.querySelector('body').setAttribute('style', 'overflow:hidden;')
  supplierShow.value = false;
  FormInfo.value.FromBasicFun(supplyType.value)
  return
  router.push({
    path: '/editSupply',
  });
}




function supplyConfirm(value) {
  const newdata = JSON.parse(JSON.stringify(value));
  supplierContactName.value = newdata.contactName;
  supplierContactMobileNo.value = newdata.contactMobileNo;
  supplierName.value = newdata.name;
  supplierCreditCode.value = newdata.creditCode;
  supplierShow.value = false;

  supplierContactIdCard.value = newdata.contactIdCard;
}
function changesupply(val){
  if(val ==1){
    labelName.value = "供应商联系人";
    labelPhone.value ="供应商手机号";
    nameType.value= "供应商名称"
  }else{
    labelName.value = "个体户联系人";
    labelPhone.value ="个体户手机号";
    nameType.value= "个体户名称"
  }
  // supplierContactName.value = "";
  // supplierContactMobileNo.value = "";
  // supplierName.value = "";
  // supplierCreditCode.value = "";
  // supplierShow.value = false;
  // supplierContactIdCard.value = "";

}
function CarConfirm(value) {
  const newdata = JSON.parse(JSON.stringify(value));
  licensePlateNo.value = newdata.licensePlateNo;
  carType.value = newdata.carType;
  enterCarID.value = newdata.id;
  showCarCode.value = false;
}

function clearBasicFromData(){
  enterName.value = "";
  enterTel.value = "";
  licensePlateNo.value = "";
  carType.value = "";
  regEntryDate.value = "";
  originProvinceCode.value = "";
  originProvinceName.value = "";
  originCityCode.value = "";
  originCityName.value = "";
  originDistrictCode.value = "";
  originDistrictName.value = "";
  productOrigin.value ="";
  supplyType.value = "1" ;
  supplierCreditCode.value = "";
  supplierName.value = "";
  supplierContactName.value = "";
  supplierContactMobileNo.value = "";
  supplierContactIdCard.value = "";
}
//编辑时候回去详情
function dataFromFather(basicData) {

 let  regEntryNewDate = basicData.regEntryDate ? dayjs(basicData.regEntryDate).format("YYYY-MM-DD HH:mm"):'';
 let  productNewOrigin = basicData.originProvinceName ? basicData.originProvinceName + "/" +basicData.originCityName +"/" +basicData.originDistrictName:'';
  enterName.value = basicData.merchantName;
  enterTel.value = basicData.merchantContactMobileNo;
  licensePlateNo.value = basicData.licensePlateNo;
  carType.value = basicData.carType;
  regEntryDate.value = basicData.copyTYPE ?  '' : regEntryNewDate;
  originProvinceCode.value = basicData.originProvinceCode;
  originProvinceName.value = basicData.originProvinceName;
  originCityCode.value = basicData.originCityCode;
  originCityName.value = basicData.originCityName;
  originDistrictCode.value = basicData.originDistrictCode;
  originDistrictName.value = basicData.originDistrictName;
  productOrigin.value =productNewOrigin;
  supplyType.value = basicData.isOwnProduct == false ? "1" : "2";
  changesupply(supplyType.value)
  supplierCreditCode.value = basicData.supplierCreditCode;
  supplierName.value = basicData.supplierName?basicData.supplierName:basicData.supplierContactName;
  supplierContactName.value = basicData.supplierContactName;
  supplierContactMobileNo.value = basicData.supplierContactMobileNo;
  supplierContactIdCard.value = basicData.supplierContactIdCard;


  setTimeout(function() {
    store.commit("changeBase" , basicData.regEntryDate )
  }, 100);
}

function entryTimeConfirm(value) {
  regEntryDate.value = dayjs(value).format("YYYY-MM-DD HH:mm");
  ShowentryTime.value = false;
  store.commit("changeBase",dayjs(value).format("YYYY-MM-DD HH:mm") + ":00" )
}

function selectCarCode() {
  showCarCode.value = true;
}

// 传数据给父组件的方法
const basicObjDataFun = () => {
  return {
    enterName: enterName.value,
    enterTel: enterTel.value,
    regEntryDate: regEntryDate.value?regEntryDate.value + ":00" :'',
    licensePlateNo: licensePlateNo.value, //车牌号
    originProvinceCode: originProvinceCode.value, //货源地
    originProvinceName: originProvinceName.value,
    originCityCode: originCityCode.value,
    originCityName: originCityName.value,
    originDistrictCode: originDistrictCode.value,
    originDistrictName: originDistrictName.value,
    isOwnProduct: supplyType.value == "1" ? false : true, //供应商类型,个体户?
    supplierCreditCode: supplyType.value == "1" ? supplierCreditCode.value : "", //社会信用码
    supplierName: supplyType.value == "1" ? supplierName.value : "", //供应商名称
    supplierContactName: supplierContactName.value, //供应商联系人
    supplierContactMobileNo: supplierContactMobileNo.value, //供应商联系方式
    supplierContactIdCard:supplyType.value == "1" ? "" : supplierContactIdCard.value, //身份证
    carType: carType.value,
  };
};

defineExpose({ basicObjDataFun, dataFromFather,clearBasicFromData });
</script>
  
  <style scoped>
  .add-supply{
    color: white;
    text-align: center;
    background: #1989fa;
    width: 100px;
    height: 40px;
    line-height: 40px;
    margin: auto;
    z-index: 99;
    position: relative;
    bottom: 8px;
    border-radius: 25px;
  }

  .ground-span{
    
    background: #F0F2F5!important;
    width: 100%;
    height: 10px;
  }
  </style>
  


<template>
  <div class="registe_page" >
    <!-- 商品信息 -->

    <van-form class="form_registe" v-show="showForm"  label-width="110px">
      <van-cell-group>
        <register-basic-info ref="registerBasicRef" @ListenTimeArea="ChangeTimeArea"></register-basic-info>
        <div class="line-all"></div>
        <register-driver-info ref="driverSafeReportRef"></register-driver-info>
        <div class="line-all"></div>
        <register-product-info ref="registerProductRef" @child-click="receiveGoodsFun"></register-product-info>
        <div class="line-all"></div>

        <div class="basic-box">
          <div class="registration_namebox_between">
            <div class="registration_left_name">食品安全承诺</div>
          </div>
          <!-- 編輯時候已同意显示 -->
         

        
          <div class="promise-outside" id="promiseBox">
            <div  class="promise-box" >
              <h3 class="promise-name">食用农产品进场登记食品安全承诺书</h3>
              <div class="promise-text">
                我对登记的食用农产品作出如下承诺:<br />
                1、承诺严格按照国家食品安全法规和相关标准,从合格的生产厂家或农户采购食用农产品<br />
                2、承诺不使用禁用农业兽药,停用兽药和非法添加物。<br />
                3、承诺常规农药和兽药残留量在允许范围内。<br />
                4、保证对承诺的真实性负责。<br />
                <div class="promise-business">张家港市青草巷农副产品批发市场</div>
                <div  class="promise-booth">{{ BoothName }} {{ BoothArea }}/{{ BoothNumber }}</div>
                <div class="signature-box">
                  <div class="signature-name">
                    <div>承诺人签名:</div>
                    <span class="promise_success" v-if="promiseStatus == true">
                      <img
                        style="border: none"
                        @click="yuLanImg(promiseImg)"
                        :src="promiseImg"
                        alt=""
                      />
                    </span>
                  </div>
                  <div class="promise-time">日期 :{{signatureDate}}</div>
                </div>
              </div>
              <div class="promise-goods">
                <div class="annex-name">附{{annexTime}}进货承诺品种名单:</div>
                <div class="annex-area">货源地:{{ annexArea }}</div>
                <div class="annex-area">车牌号:{{ annexLicensePlateNumber }}</div>
                <div class="annex-table">
                  <div class="border-grid">
                    <span v-for="item in annexGoods" :key="item.id" class="border-grid-item">
                      {{ item.goodsCustomName }}:{{ item.productNum }}{{ item.unit }}</span>
                      <span v-for="i in 3-(annexGoods.length%3||3)" :key="i" class="border-grid-item" />
                  </div>
                  
                </div>
              </div>
            </div>
          </div>
          <div  class="between_right" @click="goPromise">在线签署承诺</div>
          
          


          
          
        </div>
        
      </van-cell-group>

      <div class="targetbox" ref="scrollRef">
        <van-button 
          @click="clickRequest" 
          :loading="loadSubmit" 
          round 
          block  
          type="primary" 
          native-type="submit"
        > 保存
        </van-button>


        
      </div>
    </van-form>
  </div>
  <agreeText

    v-show="showForm == false"
    @fatherMethod="fatherMethod"
    ref="agreeRef"
  ></agreeText>
</template>

<script setup>
import "@/assets/css/protocol.css";
import dayjs from "dayjs";
import { useRouter, useRoute,onBeforeRouteLeave, onBeforeRouteUpdate } from "vue-router";
import { onMounted, nextTick, ref, unref,watch } from "vue";
import { Toast,ImagePreview} from "vant";
import { FormValidation,isMobile,strChange } from "@/util/util";
import registerBasicInfo from "@/components/registerBasicInfo.vue";
import agreeText from "./agreeText.vue";
import registerDriverInfo from "@/components/registerDriverInfo.vue";
import registerProductInfo from "@/components/registerProductInfo.vue";
import html2canvas from 'html2canvas'   
import { upLoadImg } from "@/request/UploadFile.js";
import {
  registerAdd,
  registerDetails,
  registerEdit,
} from "@/request/registerApi.js";

import store from '@/store'
const route = useRoute();
const router = useRouter();
const registerBasicRef = ref();
const driverSafeReportRef = ref();
const registerProductRef = ref();
const scrollRef = ref()
const agreeRef = ref();
const saveShow = ref(true);
const DetailID = ref("");


const showForm = ref(true);
const promiseStatus = ref(false);
const promiseImg = ref("");
const createOnFail = ref(false);
const loadSubmit = ref(false);
const PreviewID = ref('')
const AgreementBook =ref("");
const signatureDate =ref(dayjs().format('YYYY-MM-DD'))
const scrollHeight =ref(0)
const judgeedit= ref(false)
const BoothArea= ref("");
const BoothNumber= ref("");
const BoothName= ref("")

const annexGoods= ref([])
const annexTime = ref("");
const annexArea = ref("");

const annexLicensePlateNumber = ref("");



onBeforeRouteLeave((to, from,next) => {
  // if (to.name !== 'editSupply') {
  //   changeRouterKeepAlive(from.name , true);
    // } else {
  //   changeRouterKeepAlive(from.name , true);
    // }



  if(from.query.id== undefined){  //新增的时候离开
    let newdata = registerBasicRef.value.basicObjDataFun()
    let CacheData={
      ...newdata,
      persons:driverSafeReportRef.value.getDriverDataFun(),
      items:registerProductRef.value.productDataFun()
    }
    // 防疫信息
    store.commit("changeRegistration",CacheData )

  }
  next();
})

const ChangeTimeArea = (TimeAreaValue) =>{
  annexTime.value = TimeAreaValue[0]?dayjs(TimeAreaValue[0]).format("YYYY-MM-DD"):"";
  annexArea.value = TimeAreaValue[1];
  annexLicensePlateNumber.value = TimeAreaValue[2];
 
}

const receiveGoodsFun = (value) => {
  annexGoods.value = value
  
}
//开始
onMounted(() => {
  BoothNumber.value = JSON.parse(sessionStorage.getItem("storageSubject")).merchantInfo.stallCompositeInfo;
  BoothArea.value = JSON.parse(sessionStorage.getItem("storageSubject")).merchantInfo.stallArea.name;
  BoothName.value = JSON.parse(sessionStorage.getItem("storageSubject")).merchantInfo.name

  console.log(router.currentRoute.value.query.id)
  console.log(store.state.RegistrationInfo)
  console.log(JSON.stringify(store.state.RegistrationInfo) != '{}')

  // 新增返回后缓存的数据
  if(router.currentRoute.value.query.id == undefined && JSON.stringify(store.state.RegistrationInfo) != '{}'){
    cacheFun(store.state.RegistrationInfo)
  }else{
    //  cacheFun(store.state.RegistrationInfo)
  }

  //编辑的时候调用
  if (router.currentRoute.value.query.id) {
    DetailID.value = router.currentRoute.value.query.id;
    PreviewID.value = router.currentRoute.value.query.id;
    getDetail(router.currentRoute.value.query.id);
  }

  // 复制时候调用
  if (router.currentRoute.value.query.copyData) {
    copyDetail(JSON.parse(router.currentRoute.value.query.copyData));
  }
});
function cacheFun(cachedata){
  console.log("新增缓存的数据")
  console.log(cachedata)
  registerBasicRef.value.dataFromFather(cachedata);
  driverSafeReportRef.value.temporarilyCacheDriver(cachedata);
  registerProductRef.value.TemporarilyCacheProduct(cachedata);


}

function yuLanImg(val){
  ImagePreview({
        images: [val],
        showIndex: true,
        loop: false,
       
      });
}

function clearData(){
  registerBasicRef.value.clearBasicFromData();
  driverSafeReportRef.value.clearCacheDriverData();
  registerProductRef.value.clearCacheProductData();
}


function copyDetail(copyVal){
  copyVal.copyTYPE = true
  registerBasicRef.value.dataFromFather(copyVal);
  driverSafeReportRef.value.SafeReportDetail(copyVal);
  registerProductRef.value.dataDetails(copyVal);
}
function getDetail(id) {
  registerDetails(id)
    .then((res) => {
      createOnFail.value = res.data.approvalStatus == "UN_PASSED" ? true : false;
      promiseStatus.value = res.data.isPromiseSigned;
      promiseImg.value = res.data.promiseSignedImageUrl;
      AgreementBook.value = res.data.safetyCommitmentUrl;
      signatureDate.value = res.data.safetyCommitmentSignedDate;
      registerBasicRef.value.dataFromFather(res.data);
      driverSafeReportRef.value.SafeReportDetail(res.data);
      registerProductRef.value.dataDetails(res.data);
    })
    .catch((error) => {});
}





function goTop(){
  document.body.scrollTop = document.documentElement.scrollTop = 0
}




function goodsTotalQuantity(item){
  if(item.productNum){
      return Number(item.productNum)*Number(item.netContent) * multipliedByUnit(item.netContentUnit) ;
    }
}
function multipliedByUnit(val){
  if(val =='kg'){
    return 1
  }
  if(val == 'L'){
    return 1
  }
  if(val == 'l'){
    return 1
  }
  if(val == 'ml'){
    return 0.001
  }
  if(val == 'ML'){
    return 0.001
  }
  if(val == 'g'){
    return 0.001
  }
  
}


function SignAgreeFun (){
  var promise = new Promise(function(resolve,reject){
    html2canvas(document.getElementById('promiseBox'),{
    scale: 2, 
    logging: false, 
    useCORS: true, 
    allowTaint: false,
  }).then(canvas=>{
    var imgurl = canvas.toBlob((blob)=>{
        //以时间戳作为文件名 实时区分不同文件 按需求自己定义就好
        let filename = `${new Date().getTime()}.jpg`;
        //转换canvas图片数据格式为formData
        let file2 = new File([blob], filename, {type: 'image/jpg'});
        let formData = new FormData();
        formData.append('image', file2);
        upLoadImg(formData).then((res) => {
          console.log(res.data)
          resolve(res.data.imageUrl)
          
        })
      .catch((error) => {
        console.log(error);
      })
      .finally((end) => {

      });   
    })
  });
    
})
  return promise
}
// https://www.zhihu.com/question/468277979
function clickRequest (){

  // 新增 签名  不签名
  // 编辑 签名  不签名


  //编辑 签名
  if(DetailID.value){
      //编辑的逻辑
    if(judgeedit.value==true){ //编辑 由不同意改为同意
      SignAgreeFun().then(result=>{
        AgreementBook.value = result;
        console.log("sssssssss")
        submitFun()
      })
    }else{
      submitFun()
    }
  }else{
    // 新增的逻辑
    if(promiseStatus.value){  //新增且签名
      SignAgreeFun().then(result=>{
        AgreementBook.value = result;
        submitFun()
      })
    }else{    //新增不签名
      submitFun()
    }
  }
  return
  

}

//提交
function submitFun() {
  
  // 入场基本信息处理
  let basicInforData = registerBasicRef.value.basicObjDataFun();
  let FormData=  FormValidation(basicInforData);

  //基本信息验证
  if(FormData.JudgmentData==false){
    goTop()
    Toast.fail(FormData.tipsText);
    return
  }
  //车牌号提交时候转换
  basicInforData.licensePlateNo = strChange(basicInforData.licensePlateNo)


  //司机防疫信息数据
  let driveInfoData = driverSafeReportRef.value.getDriverDataFun();
  const driveObjData = JSON.parse(JSON.stringify(driveInfoData));
  const persons = driveObjData.map((each) => {
    return {
      name: each.driverName,
      mobileNo:each.driverPhone,
      healthCodeImageUrl: each.healthImg,
      tripCodeImageUrl: each.travelImg,
      nucleicAcidTestProofImageUrl: each.proveImg,
    };
  });


  if(isMobile(persons[0].mobileNo) == false){
    goTop()
    Toast.fail('司机手机号格式不对');
    return
  }
  
  // 入场的货物处理
  let goodsData = registerProductRef.value.productDataFun();
  const newdata = JSON.parse(JSON.stringify(goodsData));
  if(newdata.length<1){
    Toast.fail("请添加品种");
    return
  }

  let postProduct = newdata.map((each) => {
    return {
      goodsName: each.productName,
      goodsId: each.goodsID,
      goodsNetContent: each.netContent,
      goodsNetContentUnit: each.netContentUnit,
      goodsUnit: each.unit,
      purchaseNum: each.productNum ? each.productNum : "",
      proofFileUrls: each.ProveImg,

      isOwnProduct:each.isOwnProduct,
      supplierCreditCode:each.supplierCreditCode,
      supplierName:each.supplierName,
      supplierContactName:each.supplierContactName,
      supplierContactMobileNo:each.supplierContactMobileNo,
      supplierContactIdCard:each.supplierContactIdCard,
      goodsTotalQuantity:goodsTotalQuantity(each)

    };
  });


  loadSubmit.value = true;

  let postmaindata = {
    ...basicInforData,
    persons: persons,
    items: postProduct,
    goodsTotalQuantity: newdata[0].goodsTotalQuantity ? newdata[0].goodsTotalQuantity :0,
  };
  console.log(postmaindata)
  // 是否承诺
  postmaindata.isPromiseSigned = promiseStatus.value;
  postmaindata.promiseSignedImageUrl = promiseImg.value;
  postmaindata.safetyCommitmentUrl = AgreementBook.value;
  postmaindata.safetyCommitmentSignedDate = signatureDate.value;

  if (DetailID.value) {
    if (!createOnFail.value) { 
      //调用编辑按钮
      postmaindata.id = DetailID.value;
      registerEdit(postmaindata)
        .then((res) => {
          if(res){
            PreviewID.value = res.data.id 
            Toast.success("保存成功");
            goPreview()
          }
          
          // router.back();
        })
        .catch((error) => {})
        .finally((end) => {
          loadSubmit.value= false
        });
    } else {
      
      //未通过重新新创建
      postmaindata.id = '';
      postmaindata.originalRegId = DetailID.value;
      registerAdd(postmaindata)
        .then((res) => {
          if(res){
            createOnFail.value =false
            getDetail(res.data.id)
            Toast.success("保存成功");
            PreviewID.value = res.data.id 
            router.push({
              path: "/newRegistration",
              query: {
                id: res.data.id,
              },
            });
            goPreview()
          }
        })
        .catch((error) => {})
        .finally((end) => {
          loadSubmit.value= false
        });
    }
  } else {
    
    //新增
    registerAdd(postmaindata)
      .then((res) => {
        if(res){
          PreviewID.value = res.data.id 
          saveShow.value = false;
          Toast.success("保存成功");
          // router.push({
          //   path: "/newRegistration",
          //   query: {
          //     id: res.data.id,
          //   },
          // });
          clearData()
          goPreview()
        }
        
      })
      .catch((error) => {})
      .finally((end) => {
        loadSubmit.value= false
      });
  }


}

function goPreview(){
  setTimeout(function() {
    router.replace({path:'/registeredPreview',query:{id: PreviewID.value}})
    
  }, 100);
}

function fatherMethod(promiseVal, imgval) {
  promiseStatus.value = promiseVal;
  promiseImg.value = imgval;
  console.log(promiseImg.value)
  showForm.value = true;
  judgeedit.value =true;

  signatureDate.value = dayjs().format('YYYY-MM-DD');

  setTimeout(function() {
    
    nextTick(()=>{
      document.body.scrollTop = document.documentElement.scrollTop = 1000
    })
    
  }, 100);

}
function goPromise() {
  showForm.value = false;
  agreeRef.value.productDataFun(promiseImg.value);
}








</script>



<style>
.form_registe .van-cell-group{
  background: white!important;


}

[class*=van-hairline]:after {
    position: absolute;
    box-sizing: border-box;
    content: " ";
    pointer-events: none;
    top: -50%;
    right: -50%;
    bottom: -50%;
    left: -50%;
    border: 0 solid white!important;
    transform: scale(.5);
}
.between_left{
  display: flex;
}

.promise_error {
  color: #ee0a24;
}

</style>

<style scoped>







.promise-name{
  text-align: center;
  font-size: 17px;
  padding: 5px;
  margin: 0px;
}



.targetbox{
  width: 100%;
  box-sizing: border-box;
  padding: 8px 14px;
}

.commitment-con {
  box-sizing: border-box;
  padding: 4px 8px;
}
.registe_page {
  background: white;
  width: 100%;
  box-sizing: border-box;
}
.form_registe {
  box-sizing: border-box;
  position: relative;
  /* background: #F0F2F5; */
}
.end_submit {
  margin-bottom: 20px;
}
.uplist {
  display: flex;
}
.Warn_tips {
  font-size: 14px;
  color: #ee0a24;
}
.add_new {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #1989fa;
  width: 120px;
  padding: 8px 10px;
  color: #1989fa;
  margin: auto;
}
.worn_botton {
  font-size: 14px;
  color: #ee0a24;
  border: 1px solid #ee0a24;
  padding: 3px 4px;
  text-align: center;
  border-radius: 4px;
}

.item_up {
  position: relative;
  margin-right: 30px;
  width: 80px;
  height: 80px;
}
.item_up span {
  position: absolute;
  width: 80px;
  top: 52px;
  font-size: 12px;
  color: rgba(69, 90, 100, 0.6);
  text-align: center;
  z-index: 99;
}
.between_right {
  background: red;
  color: white;
  padding: 6px 6px;
  border-radius: 4px;
  margin: 15px auto;
  width: 130px;
  text-align: center;
  
}
</style>

相关文章

网友评论

      本文标题:vue3 watch

      本文链接:https://www.haomeiwen.com/subject/nadpmdtx.html