<template>
  <div class="coldfood">
    <div class="search-wrapper">
      <el-form :inline="true" :model="searchForm" class="search_form">
        <el-form-item label="联系人">
          <el-input v-model="searchForm.name" placeholder="请输入联系人名称" @keyup.enter.native="onSubmit"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号码" @keyup.enter.native="onSubmit"></el-input>
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="searchForm.state" placeholder="请选择预约状态" style="width: 100%">
            <el-option v-for="item in options" :key="item.state" :label="item.stateName" :value="item.state">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="searchForm.addressCode" placeholder="请选择仓库" style="width: 100%">
            <el-option v-for="item in addressList" :key="item.addressCode" :label="item.company"
              :value="item.addressCode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-wrapper">
      <table-template :tableData="tableData" :tableColumns="tableColumns" :loading="loading" :pagination="pagination"
        @Jump="jumpPage">
        <el-table-column key="stateName" prop="onlineName" label="预约状态" align="center" width="150">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type">{{ scope.row.stateName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" round @click="view(scope.row)">查看</el-button>
            <el-button v-if="scope.row.state === 11" type="success" size="mini" round @click="pass(scope.row)">通过
            </el-button>
            <el-button v-if="
              scope.row.state === 1  &&
              scope.row.storageInState === 0
            " type="success" size="mini" round @click="storageIn(scope.row)">预约入库</el-button>
            <el-button v-if="scope.row.state === 12" type="success" size="mini" round @click="storageVerify(scope.row)">
              入库审核</el-button>
            <el-button v-if="
              scope.row.state === 11 ||
              scope.row.state === 1 ||
              scope.row.state === 12
            " type="danger" size="mini" round @click="deny(scope.row)">拒绝</el-button>
            <el-button v-if="scope.row.state === 5" type="success" size="mini" round @click="print(scope.row)">打印出库证明
            </el-button>
          </template>
        </el-table-column>
      </table-template>
    </div>
    <el-dialog title="申报单详情" :visible.sync="viewShow" width="800px" :close-on-press-escape="false">
      <div class="content">
        <div class="record">
          <div class="cell_title">操作记录</div>
          <div class="cell" v-for="item in record" :key="item.createTime">
            <p class="label">
              {{ item.state
              }}<span style="color: red; font-size: 12px" v-if="item.reason">({{ item.reason }})</span>
            </p>
            <div class="info">
              <p>操作人：{{ item.name }}</p>
              <p style="margin-left: 20px">操作时间：{{ item.createTime }}</p>
            </div>
          </div>
        </div>
        <div class="goods">
          <div v-if="viewDetail.state === 9">
            <div class="cell_title">出库信息</div>
            <div class="cell" style="display:flex;">
              <p class="label" style="width:150px;">出库证明</p>
              <div class="img">
                <el-image class="smallImg" v-if="viewDetail.driverUrl" style="height: 150px; max-width: 120px"
                  :src="viewDetail.driverUrl" :preview-src-list="[viewDetail.driverUrl]" :z-index="7777777">
                </el-image>
                <div class="driverUrl" v-for="(item,index) in viewDetail.listDriverUrl" :key="index">
                  <el-image style="height: 150px; max-width: 120px" :src="item" :preview-src-list="[item]"
                    :z-index="7777777">
                  </el-image>
                </div>
              </div>
            </div>
            <div class="cell">
              <p class="label">出库车牌号</p>
              <p class="value">{{ viewDetail.deliveryCar }}</p>
            </div>
            <div class="cell">
              <p class="label">出库司机姓名</p>
              <p class="value">{{ viewDetail.deliveryName }}</p>
            </div>
          </div>
          <div class="cell_title">联系人信息</div>
          <div class="cell">
            <p class="label">联系人姓名</p>
            <p class="value">{{ viewDetail.name }}</p>
          </div>
          <div class="cell">
            <p class="label">手机号码</p>
            <p class="value">{{ viewDetail.phone }}</p>
          </div>
          <div class="cell_title">车辆信息</div>
          <div class="cell">
            <p class="label">车牌号</p>
            <p class="value">{{ viewDetail.carNumber }}</p>
          </div>
          <div class="cell">
            <p class="label">司机姓名</p>
            <p class="value">{{ viewDetail.driverName }}</p>
          </div>
          <div class="cell">
            <p class="label">联系方式</p>
            <p class="value">{{ viewDetail.driverPhone }}</p>
          </div>
          <div class="cell_title">仓库信息</div>
          <div class="cell">
            <p class="label">仓库</p>
            <p class="value">{{ viewDetail.address }}</p>
          </div>
          <div class="cell_title">照片信息</div>
          <div class="photo">
            <div class="pitem" v-for="photo in viewDetail.picture" :key="photo.pictureType">
              <el-image style="height: 100px; max-width: 150px" :src="photo.picture" :preview-src-list="[photo.picture]"
                :z-index="7777777">
              </el-image>
              <p>
                {{
                photo.pictureType === 4
                ? "驾驶员苏康码"
                : photo.pictureType === 7
                ? "驾驶员7天内核酸检测报告"
                : photo.pictureType === 5
                ? "营业执照照片"
                : photo.pictureType === 6
                ? "食品经营许可证"
                : "消毒证明"
                }}
              </p>
            </div>
          </div>
          <div class="cell_title">商品信息</div>
          <el-tabs type="card" style="padding: 0 10px">
            <el-tab-pane v-for="item in viewDetail.goods" :key="item.code" :label="item.goodsName">
              <div class="cell" v-if="item.storageInState">
                <p class="label">预约入库情况</p>
                <p class="value value1" v-if="item.storageInState == 0">尚未预约入库</p>
                <p class="value value2" v-if="item.storageInState == 1">同步成功</p>
              </div>
              <div class="cell cell2" v-if="item.storageOutState">
                <p class="label">消杀出库情况</p>
                <p class="value value1" v-if="item.storageOutState == 0">尚未消杀出库</p>
                <p class="value value2" v-if="item.storageOutState == 1">同步成功</p>
              </div>
              <div class="cell">
                <p class="label">货物商品类型</p>
                <p class="value">{{ item.goodsStateName }}</p>
              </div>
              <div class="cell" v-if="(item.storageInState != null || item.storageOutState != null) && item.hsName">
                <p class="label">货物商品分类</p>
                <p class="value">{{ item.hsName }}</p>
              </div>
              <div class="cell">
                <p class="label">报关单号(海关编号)</p>
                <p class="value">{{ item.customs }}</p>
              </div>
              <div class="cell">
                <p class="label">货主名称</p>
                <p class="value">{{ item.shipper }}</p>
              </div>
              <div class="cell">
                <p class="label">统一社会信用代码</p>
                <p class="value">{{ item.credit }}</p>
              </div>
              <div class="cell" v-if="(item.storageInState != null || item.storageOutState != null) && item.certNo">
                <p class="label">检验检疫证编号</p>
                <p class="value">{{ item.certNo }}</p>
              </div>
              <div class="cell" v-if="(item.storageInState != null || item.storageOutState != null) && item.entryDate">
                <p class="label">入境时间</p>
                <p class="value">{{ item.entryDate }}</p>
              </div>
              <div class="cell"
                v-if="(item.storageInState != null || item.storageOutState != null) && item.portEntryName">
                <p class="label">入境口岸</p>
                <p class="value">{{ item.portEntryName }}</p>
              </div>
              <div class="cell" v-if="(item.storageInState != null || item.storageOutState != null) && item.sourceType">
                <p class="label">食品来源</p>
                <p class="value">{{ item.sourceType }}</p>
              </div>
              <div class="cell">
                <p class="label">集装箱号</p>
                <p class="value">{{ item.container }}</p>
              </div>
              <div class="cell">
                <p class="label">商品名称</p>
                <p class="value">{{ item.goodsName }}</p>
              </div>
              <div class="cell" v-if="(item.storageInState != null || item.storageOutState != null) && item.consigner">
                <p class="label">发货人</p>
                <p class="value">{{ item.consigner }}</p>
              </div>
              <div class="cell">
                <p class="label">入库重量（千克）</p>
                <p class="value">{{ item.weight }}</p>
              </div>
              <div class="cell"
                v-if="(item.storageInState != null || item.storageOutState != null) && item.tradeWeight">
                <p class="label">报关单重量（千克）</p>
                <p class="value">{{ item.tradeWeight }}</p>
              </div>
              <div class="cell">
                <p class="label">件数</p>
                <p class="value">{{ item.number }}</p>
              </div>
              <div class="cell"
                v-if="(item.storageInState != null || item.storageOutState != null) && item.specification">
                <p class="label">包装规格（千克/件）</p>
                <p class="value">{{ item.specification }}</p>
              </div>
              <div class="cell">
                <p class="label">注册号</p>
                <p class="value">{{ item.register }}</p>
              </div>
              <div class="cell">
                <p class="label">原产地</p>
                <p class="value">{{ item.placeOrigin }}</p>
              </div>
              <div class="cell">
                <p class="label">生产日期</p>
                <p class="value">{{ item.productionTime }}</p>
              </div>
              <div class="cell"
                v-if="(item.storageInState != null || item.storageOutState != null) && item.verifyMonth">
                <p class="label">保质期（月）</p>
                <p class="value">{{ item.verifyMonth }}</p>
              </div>
              <div class="cell">
                <p class="label">生产批号</p>
                <p class="value">{{ item.productionNumber }}</p>
              </div>
              <div class="cell">
                <p class="label">商品流向地区</p>
                <p class="value">{{ item.goodsFlowRegion }}</p>
              </div>
              <div class="cell">
                <p class="label">商品流向(详细地址)</p>
                <p class="value">{{ item.goodsFlowAddress }}</p>
              </div>
              <div class="cell">
                <p class="label">企业经营类型</p>
                <p class="value">{{ item.operateName }}</p>
              </div>
              <div class="photo">
                <div class="pitem" v-for="photo in item.pictureList" :key="photo.pictureType">
                  <el-image style="height: 100px; max-width: 150px" :src="photo.picture"
                    :preview-src-list="[photo.picture]" :z-index="7777777">
                  </el-image>
                  <!-- <img :src="photo.picture" alt="" /> -->
                  <p>
                    {{
                    photo.pictureType === 1
                    ? "报关单照片"
                    : photo.pictureType === 2
                    ? "货物清单照片"
                    : "检疫证照片"
                    }}
                  </p>
                </div>
              </div>
              <div v-if="item.goodsTracing && item.goodsTracing.length > 0">
                <div v-for="trace in item.goodsTracing" :key="trace.code">
                  <div class="cell">
                    <p class="label">商品流向单位（个人）</p>
                    <p class="value">{{ trace.company }}</p>
                  </div>
                  <div class="cell">
                    <p class="label">商品流向重量(KG)</p>
                    <p class="value">{{ trace.goodsWeight }}</p>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TableTemplate from "@/components/Table";
import { changeList, setName, setTel } from "@/utils";
import {
  getList,
  updateState,
  detail,
  record,
  // getPrint,  老
  getOutPrinting, //新
  getAddress,
  storageIn,
  storageVerify,
} from "@/api/coldfood";
// import { fromDate } from "@/utils";
import { Message } from "element-ui";
// import docxtemplater from "docxtemplater";
// import PizZip from "pizzip";
// import JSZipUtils from "jszip-utils";
// import { saveAs } from "file-saver";
import { downFile } from '@/utils/common.js'

export default {
  components: { TableTemplate },
  data() {
    return {
      userName: "",
      searchForm: {
        name: "",
        phone: "",
        state: "",
        addressCode: "",
      },
      loading: false,
      options: [
        {
          state: "",
          stateName: "全部",
          color: "",
        },
        {
          state: 0,
          stateName: "待App审核",
          type: "warning",
        },
        {
          state: 11,
          stateName: "待管理后台审核",
          type: "warning",
        },
        {
          state: 1,
          stateName: "待预约入库",
          type: "warning",
        },
        {
          state: 2,
          stateName: "已驳回",
          type: "danger",
        },
        {
          state: 3,
          stateName: "已撤回",
          type: "info",
        },
        {
          state: 4,
          stateName: "已入库(待检测)",
          type: "warning",
        },
        {
          state: 7,
          stateName: "检测通过(待消杀)",
          type: "warning",
        },
        {
          state: 8,
          stateName: "检测未通过(待灭活)",
          type: "danger",
        },
        {
          state: 5,
          stateName: "消杀通过(待出库)",
          type: "warning",
        },
        // {
        //   state: 6,
        //   stateName: "消杀未通过",
        //   type: "danger"
        // },
        {
          state: 9,
          stateName: "已出库",
          type: "success",
        },
        {
          state: 10,
          stateName: "已灭活",
          type: "info",
        },
        {
          state: 12,
          stateName: "待入库审核",
          type: "warning"
        },
        {
          state: 13,
          stateName: "待入库",
          type: "warning"
        }
      ],
      addressList: [
        {
          addressCode: "",
          company: "全部",
        },
      ],
      tableData: [],
      tableColumns: [
        {
          key: "driverNo",
          label: "货物编号",
          width: 200,
        },
        {
          key: "name",
          label: "联系人",
          width: 150,
        },
        {
          key: "phone",
          label: "手机号",
          width: 180,
        },
        {
          key: "carNumber",
          label: "车牌号",
          width: 150,
        },
        {
          key: "determineTime",
          label: "预约入库时间",
          width: 220,
        },
        {
          key: "createTime",
          label: "预约时间",
          width: 220,
        },
      ],
      pagination: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      viewShow: false,
      viewDetail: {},
      record: [],
    };
  },
  methods: {
    init() {
      this.loading = true;
      let params = {
        name: this.searchForm.name,
        phone: this.searchForm.phone,
        state: this.searchForm.state,
        addressCode: this.searchForm.addressCode,
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
      };
      getList(params).then((res) => {
        // console.log('res---',res);

        this.loading = false;
        if (res.success) {
          this.pagination.total = res.data.total;
          if (res.data.total != 0) {
            this.tableData = res.data.list.map((item) => {
              (item.stateName = this.getSatusArr(item.state).stateName);
              (item.type = this.getSatusArr(item.state).type);
              return item;
            });
            if (localStorage.getItem('userName') == 'admin') {
              this.tableData = changeList(this.tableData)
            }
          } else {
            this.tableData = []
          }
        }
      });
    },
    initAddress() {
      getAddress({}).then((res) => {
        let arr = res.data.map((item) => {
          return {
            addressCode: item.code,
            company: item.company,
          };
        });
        this.addressList = this.addressList.concat(arr);
      });
    },
    jumpPage() {
      this.init();
    },
    onSubmit() {
      this.pagination.currentPage = 1;
      this.init();
    },
    view(row) {
      let params = {
        driverCode: row.driverCode,
      };
      Promise.all([detail(params), record(params)]).then((res) => {
        // console.log(res);
        this.viewDetail = res[0].data;
        if (localStorage.getItem('userName') == 'admin') {
          this.viewDetail.name = setName(this.viewDetail.name)
          this.viewDetail.phone = setTel(this.viewDetail.phone)
          this.viewDetail.driverName = setName(this.viewDetail.driverName)
          this.viewDetail.driverPhone = setTel(this.viewDetail.driverPhone)
        }
        this.record = res[1].data.reverse();
        this.viewShow = true;
      });
    },
    pass(row) {
      this.$confirm("确定通过后台审核吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            driverCode: row.driverCode,
            name: this.userName,
            state: 1,
          };
          updateState(params).then((res) => {
            console.log(res);
            Message.success("审核通过");
            this.init();
          });
        })
        .catch(() => {
          // console.log("取消审核");
        });
    },
    deny(row) {
      this.$prompt("确定拒绝该预约申报吗?确定的话，请输入拒绝原因。", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "请输入拒绝原因",
        inputType: "textarea",
      })
        .then(({ value }) => {
          if (!value) {
            this.$message.error("未输入拒绝原因");
          } else {
            let params = {
              driverCode: row.driverCode,
              name: this.userName,
              state: 2,
              driverReason: value,
              reason: value,
            };
            updateState(params).then((res) => {
              console.log(res);
              Message.success("审核拒绝");
              this.init();
            });
          }
        })
        .catch(() => {
          // console.log("取消");
        });
      // console.log(row);
    },
    storageIn(row) {
      this.$confirm("确定预约入库吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log(row);
        let params = {
          appId: row.appId,
          driverCode: row.driverCode,
          name: this.userName,
          state: 12,
        };
        storageIn(params).then((res) => {
          console.log(res);
          Message.success(res.data);
          this.init();
        });
      }).catch(() => {
        // console.log("取消审核");
      });
    },
    storageVerify(row) {
      this.$confirm("确定通过入库审核吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let params = {
          appId: row.appId,
          driverCode: row.driverCode,
          state: 13,
          name: this.userName,
        };
        storageVerify(params).then((res) => {
          console.log(res);
          Message.success(res.data);
          this.init();
        });
      }).catch(() => {
        // console.log("取消审核");
      });
    },
    // 新打印
    print(row) {
      console.log(row);
      let params = {
        appId: row.appId,
        driverCode: row.driverCode
      }
      getOutPrinting(params).then((res) => {
        let name = row.driverNo
        downFile(`${name}出库证明.zip`, new Blob([res.data]))
      })
    },
    // 老打印
    // print(code) {
    //   // console.log('code---',code);

    //   let params = {
    //     driverCode: code,
    //   };
    //   getPrint(params).then((res) => {
    //     // console.log(res);
    //     let arr = res.data;
    //     arr.goods = arr.goods.map((item, index) => {
    //       item.index = index + 1;
    //       return item;
    //     });
    //     // console.log(arr);
    //     let docxsrc = "./static/peopleout.docx"; //模板文件的位置
    //     let docxname = "出库证明"; //导出文件的名字
    //     // 读取并获得模板文件的二进制内容
    //     JSZipUtils.getBinaryContent(docxsrc, function (error, content) {
    //       // docxsrc是模板。我们在导出的时候，会根据此模板来导出对应的数据
    //       // 抛出异常
    //       if (error) {
    //         // console.log("asdasdasd");
    //         throw error;
    //       }
    //       // 创建一个PizZip实例，内容为模板的内容
    //       let zip = new PizZip(content);
    //       // 创建并加载docx templater实例对象
    //       let doc = new docxtemplater().loadZip(zip);
    //       let date = fromDate(new Date().getTime());
    //       // 设置模板变量的值
    //       doc.setData({
    //         date,
    //         ...arr, // e中的数据可以再模板中直接使用
    //       });

    //       try {
    //         // 用模板变量的值替换所有模板变量
    //         doc.render();
    //       } catch (error) {
    //         // 抛出异常
    //         let e = {
    //           message: error.message,
    //           name: error.name,
    //           stack: error.stack,
    //           properties: error.properties,
    //         };
    //         console.log(
    //           JSON.stringify({
    //             error: e,
    //           })
    //         );
    //         throw error;
    //       }

    //       // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
    //       let out = doc.getZip().generate({
    //         type: "blob",
    //         mimeType:
    //           "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    //       });
    //       // 将目标文件对象保存为目标类型的文件，并命名
    //       saveAs(out, docxname);
    //     });
    //   });
    // },
    getSatusArr(state) {
      return this.options.filter((item) => {
        return item.state === state;
      })[0];
    },
  },
  created() {
    this.userName = localStorage.getItem('userName');
    this.init();
    this.initAddress();
  },
};
</script>

<style lang="stylus" scoped>
@import '~@/stylus/common';

.content {
  max-height: 60vh;
  overflow-y: auto;

  .record {
    .cell_title {
      padding: 10px;
      border-bottom: 1px solid #eee;
      font-size: 18px;
      color: #333;
      font-weight: 600;
      text-align: left;
    }

    .cell {
      padding: 10px;
      border-bottom: 1px solid #eee;
      text-align: left;

      .label {
        font-size: 16px;
        color: #333;
      }

      .info {
        margin-top: 10px;
        display: flex;
      }
    }
  }

  .goods {
    .cell_title {
      margin-top: 20px;
      padding: 10px;
      border-bottom: 1px solid #eee;
      font-size: 18px;
      color: #333;
      font-weight: 600;
      text-align: left;
    }

    .cell {
      display: flex;
      align-items: center;
      padding: 10px;
      border-bottom: 1px solid #eee;

      .label {
        width: 150px;
        color: #999;
        text-align: left;
      }
      .img{
        display:flex;
        flex-direction: row;
        flex-wrap: wrap;
          .smallImg{
            height: 150px;
            margin: 10px 0 0 10px;
          }
          .driverUrl{
            height: 150px;
            margin: 10px 0 0 10px;
          }
      }
      

      .value {
        color: #000;
        text-align: left;
      }

      .value1 {
        color: red;
      }

      .value2 {
        color: green;
      }
    }

    .photo {
      height: 170px;
      padding: 0 20px;
      display: flex;
      align-items: center;

      .pitem {
        height: 160px;
        margin-right: 15px;

        p {
          margin-top: 10px;
          text-align: center;
          font-size: 16px;
          color: #999999;
        }
      }
    }
  }
}

::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}

::-webkit-scrollbar-thumb {
  background-color: #a1a3a9;
  border-radius: 2px;
}
</style>
