<template>
  <div class="selfreport">
    <!-- <nav-header title="自主信息录入" @back="$router.go(-1)" /> -->
    <div class="main">
      <van-form @submit="onSubmit" ref="goodsForm">
        <div class="userInfo">
          <van-field
            v-model="form.name1"
            label="申报人姓名"
            readonly
            required
            placeholder="请填写申报人姓名"
            :rules="[{ required: true, message: '请填写申报人姓名' }]"
          />
          <van-field
            v-model="form.phone1"
            label="手机号码"
            readonly
            required
            placeholder="请填写手机号码"
            :rules="[
              { required: true, message: '请填写手机号码' },
              { pattern: phoneReg, message: '请输入正确内容' },
            ]"
          />
        </div>
        <div class="carInfo">
          <div class="title">
            <div class="icon"></div>
            <p>车辆信息</p>
          </div>
          <van-field
            v-model="form.carNumber"
            label="车牌号"
            required
            placeholder="请填写车牌号"
            :rules="[{ required: true, message: '请填写车牌号' }]"
          />
        </div>
        <div
          class="carInfo"
          v-for="(driver, index) in form.drivers"
          :key="driver.driverId"
        >
          <div class="title">
            <div class="icon"></div>
            <p>司机信息</p>
            <van-icon
              v-if="index > 0"
              size="25"
              class="delete_icon"
              name="delete"
              @click="deleDriver(driver.driverId)"
            />
          </div>
          <van-field
            v-model="driver.driverName"
            label="姓名"
            required
            placeholder="请填写姓名"
            :rules="[{ required: true, message: '请填写司机姓名' }]"
          />
          <van-field
            v-model="driver.idCard"
            label="身份证号码"
            required
            placeholder="请填写身份证号码"
            :rules="[
              { required: true, message: '请填写身份证号码' },
              { pattern: idcardReg, message: '请输入正确内容' },
            ]"
          />
          <van-field
            v-model="driver.driverPhone"
            label="联系方式"
            type="number"
            required
            placeholder="请输入联系方式"
            :rules="[
              { required: true, message: '请输入联系方式' },
              { pattern: phoneReg, message: '请输入正确内容' },
            ]"
          />
        </div>
        <div class="addgoods" @click="adddriver">新增同乘人员信息</div>
        <div
          class="goodInfo"
          v-for="(item, index) in form.goods"
          :key="item.id"
        >
          <div class="info">
            <div class="title">
              <div class="icon"></div>
              <p>商品信息</p>
              <van-icon
                v-if="index > 0"
                size="25"
                class="delete_icon"
                name="delete"
                @click="delegoods(item.id)"
              />
            </div>
            <van-field
              v-model="item.customs"
              label="报关单号(海关编号)"
              required
              placeholder="请输入报关单号"
              :rules="[{ required: true, message: '请输入报关单号' }]"
            />
            <van-field
              v-model="item.shipperEnterprise"
              label="货主所属企业名称"
              required
              placeholder="请输入货主所属企业名称"
              :rules="[{ required: true, message: '请输入货主所属企业名称' }]"
            />
            <van-field
              v-model="item.credit"
              label="统一社会信用代码"
              required
              placeholder="请输入统一社会信用代码"
              :rules="[{ required: true, message: '请输入统一社会信用代码' }]"
            />
            <van-field
              v-model="item.shipper"
              label="货主联系人"
              required
              placeholder="请输入货主联系人"
              :rules="[{ required: true, message: '请输入货主联系人' }]"
            />
            <van-field
              v-model="item.shipperPhone"
              label="货主联系方式"
              type="number"
              required
              placeholder="请输入货主联系方式"
              :rules="[
                { required: true, message: '请输入货主联系方式' },
                { pattern: phoneReg, message: '请输入正确内容' },
              ]"
            />
            <van-field
              v-model="item.shipperIdCard"
              label="货主身份证号码"
              required
              placeholder="请输入货主身份证号码"
              :rules="[
                { required: true, message: '请输入货主身份证号码' },
                { pattern: idcardReg, message: '请输入正确内容' },
              ]"
            />
            <van-field
              label="是否有集装箱号"
              required
              :rules="[{ required: true, message: '请选择是否有集装箱' }]"
            >
              <template #input>
                <van-radio-group
                  v-model="item.containerState"
                  direction="horizontal"
                >
                  <van-radio :name="1">是</van-radio>
                  <van-radio :name="0">否</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <van-field
              v-model="item.goodsName"
              label="商品名称"
              required
              placeholder="请输入商品名称"
              :rules="[{ required: true, message: '请输入商品名称' }]"
            />
            <van-field
              v-model="item.placeOrigin"
              label="原产地"
              required
              placeholder="请输入原产地"
              :rules="[{ required: true, message: '请输入原产地' }]"
            />
            <van-field
              v-model="item.register"
              label="注册编号"
              required
              placeholder="注册编号"
              :rules="[{ required: true, message: '注册编号' }]"
            />
            <van-field
              v-model="item.productionTime"
              label="生产日期"
              required
              placeholder="请输入生产日期"
              :rules="[{ required: true, message: '请输入生产日期' }]"
            />
            <van-field
              v-model="item.productionNumber"
              label="生产批号"
              required
              placeholder="请输入生产批号"
              :rules="[{ required: true, message: '请输入生产批号' }]"
            />
            <van-field
              v-model="item.weight"
              label="重量(KG)"
              type="number"
              required
              placeholder="请输入总重量"
              :rules="[{ required: true, message: '请输入总重量' }]"
            />
            <van-field
              label="是否在镇江销售"
              required
              :rules="[{ required: true, message: '请选择是否在镇江销售' }]"
            >
              <template #input>
                <van-radio-group
                  v-model="item.goodsState"
                  direction="horizontal"
                >
                  <van-radio :name="1">是</van-radio>
                  <van-radio :name="0">否</van-radio>
                </van-radio-group>
              </template>
            </van-field>
          </div>
          <div class="imginfo">
            <div class="title">
              <div class="icon"></div>
              <p>上传清晰照片</p>
            </div>
            <van-field label="上传报关单照片" required>
              <template #input>
                <van-uploader
                  :after-read="afterRead"
                  v-model="item.bill"
                  max-count="1"
                />
              </template>
            </van-field>
            <van-field label="上传货物清单照片" required>
              <template #input>
                <van-uploader
                  :after-read="afterRead"
                  v-model="item.inventory"
                  max-count="1"
                />
              </template>
            </van-field>
            <van-field label="上传入境货物检验检疫证明照" required>
              <template #input>
                <van-uploader
                  :after-read="afterRead"
                  v-model="item.certificate"
                  max-count="1"
                />
              </template>
            </van-field>
            <van-field label="上传省内其他城市有效《出库证明》照片">
              <template #input>
                <van-uploader
                  :after-read="afterRead"
                  v-model="item.prove"
                  max-count="1"
                />
              </template>
            </van-field>
          </div>
        </div>
      </van-form>
      <van-button class="addgoods" block @click="addgoods"
        >新增商品信息</van-button
      >
      <div style="height: 20px"></div>
    </div>
    <van-button class="submit" block @click="send">提交</van-button>
  </div>
</template>

<script>
import Vue from "vue";
import {
  Form,
  Field,
  Button,
  Uploader,
  Icon,
  Collapse,
  CollapseItem,
  RadioGroup,
  Radio
} from "vant";
// import NavHeader from "@/components/NavHeader";
import { uploadFile, reportSelf, getSelf, updateSelf } from "@/api/coldfood";
import { phoneReg, idcardReg } from "@/utils/constant";
import { encryptByDES } from "@/utils/utils";

Vue.use(Form)
  .use(Field)
  .use(Button)
  .use(Icon)
  .use(RadioGroup)
  .use(Radio)
  .use(Uploader)
  .use(Collapse)
  .use(CollapseItem);

let goodsId = 10;
let driverId = 1;

export default {
  components: {
    // NavHeader
  },
  data() {
    return {
      userInfo: {},
      type: null,
      chainSelfCode: null,
      phoneReg,
      idcardReg,
      form: {
        name: "", // 联系人姓名
        phone: "", // 手机号码
        name1: "", // 联系人姓名
        phone1: "", // 手机号码
        carNumber: "", // 车牌号
        drivers: [
          {
            driverId: driverId,
            driverName: "", // 司机姓名
            idCard: "", // 身份证号码
            driverPhone: "" // 司机联系方式
          }
        ],
        goods: [
          {
            id: goodsId,
            customs: "", // 报关单号(海关编号)
            shipperEnterprise: "", // 货主所属企业名称
            credit: "", // 统一社会信用代码
            shipper: "", // 货主联系人
            shipperPhone: "", // 货主联系方式
            shipperIdCard: "", // 货主身份证号码
            containerState: 1, // 是否有集装箱
            goodsName: "", // 商品名称
            placeOrigin: "", // 原产地
            register: "", // 注册编号
            productionTime: "", // 生产日期
            productionNumber: "", // 生产批号
            weight: "", // 总重量
            goodsState: 1, // 是否在镇江销售
            bill: [], //报关单照片
            inventory: [], // 货物清单照片
            certificate: [], // 检疫证照片
            prove: [] // 出库证明
          }
        ]
      }
    };
  },
  methods: {
    send() {
      this.$refs.goodsForm.submit();
    },
    onSubmit() {
      const { type, chainSelfCode, form } = this;
      let phototFlag = true;
      form.goods.map(item => {
        if (
          item.bill.length <= 0 ||
          item.inventory.length <= 0 ||
          item.certificate.length <= 0 
        ) {
          this.$toast("请上传必要的清晰图片");
          phototFlag = false;
          return;
        }
      });
      if (phototFlag) {
        let params = {
          appId: 1234,
          userId: this.userInfo.userId,
          carNumber: form.carNumber,
          driverSelfList: form.drivers.map(item => {
            return {
              driverName: item.driverName,
              idCard: item.idCard,
              driverPhone: item.driverPhone
            };
          }),
          name: form.name,
          phone: form.phone,
          goodsList: form.goods.map(item => {
            var mockList = [
               {
                  pictureType: 1,
                  picture: item.bill[0].url
                },
                {
                  pictureType: 2,
                  picture: item.inventory[0].url
                },
                {
                  pictureType: 3,
                  picture: item.certificate[0].url
                },
            ]
            if(item.prove.length > 0){
              mockList.push({
                  pictureType: 4,
                  picture: item.prove[0].url
              })
            }
            return {
              appId: 1234,
              customs: item.customs,
              shipperEnterprise: item.shipperEnterprise,
              credit: item.credit,
              shipper: item.shipper,
              shipperPhone: item.shipperPhone,
              shipperIdCard: item.shipperIdCard,
              containerState: item.containerState,
              goodsName: item.goodsName,
              placeOrigin: item.placeOrigin,
              register: item.register,
              productionTime: item.productionTime,
              productionNumber: item.productionNumber,
              goodsFlowAddress: item.goodsFlowAddress,
              weight: item.weight,
              goodsState: item.goodsState,
              pictureList: mockList
            };
          })
        };
        console.log(params);
        this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true,
          message: "申报提交中..."
        });
        if (type === "edit") {
          params.code = chainSelfCode;
          updateSelf(params).then(() => {
            this.$toast.success("您的申报信息已更改，等待管理人员联系。");
            setTimeout(() => {
              this.$router.go(-1);
            }, 1000);
          });
        } else {
          reportSelf(params).then(() => {
            this.$toast.success("您的申报信息已受理，等待管理人员联系。");
            setTimeout(() => {
              this.$router.go(-1);
            }, 1000);
          });
        }
      }
    },
    init() {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "加载中..."
      });
      let params = {
        appId: 1234,
        userId: encryptByDES(this.userInfo.userId, "MnuYbhGv")
      };
      getSelf(params).then(res => {
        this.$toast.clear();
        this.chainSelfCode = res.data.chainSelfCode;
        this.form = {
          name: res.data.name,
          phone: res.data.phone,
          name1: res.data.name.substring(0,1)+(res.data.name.length == 2 ? '*' : '**'),
          phone1: res.data.phone.substring(0,3)+'****'+res.data.phone.substring(7,12),
          carNumber: res.data.carNumber,
          drivers: res.data.driverSelfList.map(item => {
            return {
              driverId: item.driverSelfCode,
              driverName: item.driverName,
              idCard: item.idCard,
              driverPhone: item.driverPhone
            };
          }),
          goods: res.data.goodsList.map(item => {
            return {
              id: item.goodsSelfCode,
              customs: item.customs,
              shipperEnterprise: item.shipperEnterprise,
              credit: item.credit,
              shipper: item.shipper,
              shipperPhone: item.shipperPhone,
              shipperIdCard: item.shipperIdCard,
              containerState: item.containerState,
              goodsName: item.goodsName,
              placeOrigin: item.placeOrigin,
              register: item.register,
              productionTime: item.productionTime,
              productionNumber: item.productionNumber,
              goodsFlowAddress: item.goodsFlowAddress,
              weight: item.weight,
              goodsState: item.goodsState,
              bill: item.pictureList
                .filter(item => {
                  return item.pictureType === 1;
                })
                .map(item => {
                  item.url = item.picture;
                  return item;
                }),
              inventory: item.pictureList
                .filter(item => {
                  return item.pictureType === 2;
                })
                .map(item => {
                  item.url = item.picture;
                  return item;
                }),
              certificate: item.pictureList
                .filter(item => {
                  return item.pictureType === 3;
                })
                .map(item => {
                  item.url = item.picture;
                  return item;
                }),
              prove: item.pictureList
                .filter(item => {
                  return item.pictureType === 4;
                })
                .map(item => {
                  item.url = item.picture;
                  return item;
                })
            };
          })
        };
      });
    },
    addgoods() {
      this.form.goods.push({
        id: goodsId + 1,
        customs: "", // 报关单号(海关编号)
        shipperEnterprise: "", // 货主所属企业名称
        credit: "", // 统一社会信用代码
        shipper: "", // 货主联系人
        shipperPhone: "", // 货主联系方式
        shipperIdCard: "", // 货主身份证号码
        containerState: "1", // 是否有集装箱
        goodsName: "", // 商品名称
        placeOrigin: "", // 原产地
        register: "", // 注册编号
        productionTime: "", // 生产日期
        productionNumber: "", // 生产批号
        weight: "", // 总重量
        goodsState: "1", // 是否在镇江销售
        bill: [], //报关单照片
        inventory: [], // 货物清单照片
        certificate: [], // 检疫证照片
        prove: []
      });
      goodsId = goodsId + 1;
    },
    adddriver() {
      this.form.drivers.push({
        driverId: driverId + 1,
        driverName: "", // 司机姓名
        idCard: "", // 身份证号码
        driverPhone: "" // 司机联系方式
      });
      driverId = driverId + 1;
    },
    delegoods(id) {
      this.form.goods = this.form.goods.filter(item => {
        return item.id !== id;
      });
    },
    deleDriver(id) {
      this.form.drivers = this.form.drivers.filter(item => {
        return item.driverId !== id;
      });
    },
    afterRead(file) {
      file.status = "uploading";
      file.message = "上传中...";
      let param = new FormData();
      param.append("file", file.file);
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "上传图片中..."
      });
      uploadFile(param)
        .then(res => {
          this.$toast.clear();
          file.status = "done";
          file.message = "上传成功";
          file.url = res.data;
        })
        .catch(err => {
          console.log(err);
          file.status = "failed";
          file.message = "上传失败";
        });
    }
  },
  created() {
    let res = sessionStorage.getItem("ZJCD-UserInfo");
    this.userInfo = JSON.parse(res);
    this.form.name = this.userInfo.realName;
    this.form.phone = this.userInfo.mobileNo;
    this.form.name1 = this.userInfo.realName.substring(0,1)+(this.userInfo.realName.length == 2 ? '*' : '**');
    this.form.phone1 = this.userInfo.mobileNo.substring(0,3)+'****'+this.userInfo.mobileNo.substring(7,12);
    this.type = this.$route.query.type;
    if (this.type === "edit") {
      this.init();
    }
  }
};
</script>

<style lang="stylus" scoped>
.selfreport {
  .main {
    height: calc(100vh - 88px);
    overflow-y: auto;

    .van-cell {
      border-bottom: 1px solid #eee;
    }

    .van-uploader__upload {
      border: 1px solid #eee;
    }

    .title {
      position: relative;
      height: 80px;
      padding: 0 20px;
      display: flex;
      align-items: center;
      background: #fff;
      border-bottom: 1px solid #eee;

      .icon {
        width: 6px;
        height: 32px;
        background: #EB4E3F;
      }

      p {
        margin-left: 10px;
        font-size: 32px;
        font-weight: 600;
        color: #333333;

        span {
          font-size: 28px;
          font-weight: 400;
          color: #333333;
        }
      }

      .delete_icon {
        position: absolute;
        right: 20px;
        line-height: 80px;
        color: #EB4E3F;
      }
    }

    .carInfo {
      margin-top: 20px;
    }

    .goodInfo {
      .info {
        margin-top: 20px;
      }

      .imginfo {
        margin-top: 20px;
      }
    }

    .addgoods {
      width: 500px;
      height: 80px;
      margin: 30px auto;
      background: #EB4E3F;
      border-radius: 40px;
      line-height: 80px;
      text-align: center;
      font-size: 36px;
      font-weight: 500;
      color: #FFFFFF;
    }

    .ordertime {
      .content {
        width: 100%;
        height: 210px;
        background: #F3F6F9;

        .cell {
          padding: 0 30px;
          height: 70px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .font {
            display: flex;
            align-items: center;

            .dot {
              width: 10px;
              height: 10px;
              background: #EB4E3F;
              border-radius: 5px;
            }

            p {
              margin-left: 20px;
              font-size: 28px;
              font-weight: 400;
              color: #333333;
            }
          }

          img {
            width: 40px;
            height: 40px;
          }
        }
      }
    }
  }

  .submit {
    width: 100%;
    height: 90px;
    background: #EB4E3F;
    font-size: 36px;
    font-weight: 500;
    color: #FFFFFF;
  }
}
</style>