<template>
  <div class="form-wrap" v-loading="isLoading" element-loading-text="正在计算中...">
    <el-form label-position="left" ref="form" :model="form" label-width="110px">
      <div class="moudle-list">
        <div class="moudle">
          <div class="title-list">
            <div v-if="memberType !== 1" @click="sendType = 1" :class=" sendType ? 'title' : 'normal-title'">
              门店地址发单
            </div>
            <div @click="sendType = 0" :class=" !sendType ? 'title' : 'normal-title'">
              个人地址发单
            </div>
          </div>

          <el-form-item :label="sendType ? '发件门店' : '发件人姓名'" required>
            <el-input v-show="!sendType" size="small" class="input" v-model="form.sendAddress.contact" placeholder="请填写发件人姓名" clearable></el-input>
            <el-input v-show="sendType" disabled size="small" class="input" v-model="name" placeholder="请填写发件门店"></el-input>
            <el-button v-show="sendType" @click="showShop(1)" class="but1 active" type="info">选择门店</el-button>
            <el-button v-show="!sendType" @click="showShop(2)" class="but1 active" type="info">常用地址</el-button>
          </el-form-item>
          <el-form-item label="发件人电话" required>
            <el-input size="small" class="phone-before" v-model="form.sendAddress.phone" placeholder="请填写发件人电话" clearable></el-input>
            <div class="phone-center">~</div>
            <el-input size="small" class="phone-after" v-model="form.sendAddress.extension" placeholder="分机号"></el-input>
          </el-form-item>
          <el-form-item label="发件人地址" required>
            <el-input size="small" v-model="form.sendAddress.address" placeholder="请选择发件人地址" disabled>
              <img @click="showMap(1)" slot="append" class="map" src="../../static/image/icon_map.png">
            </el-input>
          </el-form-item>
          <el-form-item label="楼号/门牌号">
            <el-input size="small" v-model="form.sendAddress.street" placeholder="请填写发件人楼号/门牌号" :disabled="!!sendType" clearable>
            </el-input>
          </el-form-item>
        </div>
        <div class="moudle">
          <div class="title">
            收件地址
          </div>
          <el-form-item label="收件人姓名" required>
            <el-input size="small" v-model="form.receiptAddress.contact" placeholder="请填写收件人姓名" clearable>
            </el-input>
            <el-button @click="showShop(3)" class="but1 active" type="info">常用地址</el-button>
          </el-form-item>
          <el-form-item label="收件人电话" required>
            <el-input size="small" class="phone-before" v-model="form.receiptAddress.phone" placeholder="请填写收件人电话" clearable></el-input>
            <div class="phone-center">~</div>
            <el-input size="small" class="phone-after" v-model="form.receiptAddress.extension" placeholder="分机号"></el-input>
          </el-form-item>
          <el-form-item label="收件人地址" required>
            <el-input size="small" v-model="form.receiptAddress.address" placeholder="请选择收件人地址" disabled>
              <img @click="showMap(2)" slot="append" class="map" src="../../static/image/icon_map.png">
            </el-input>
          </el-form-item>
          <el-form-item label="楼号/门牌号">
            <el-input size="small" v-model="form.receiptAddress.street" placeholder="请填写收件人楼号/门牌号" clearable>
            </el-input>
          </el-form-item>
        </div>
        <div class="moudle">
          <div class="title">
            物品信息
          </div>
          <el-form-item label="物品类型" required>
            <!-- <div class="category_box">
              <div class="item" :class="form.productId === item.id ? 'active':''" v-for="(item,i) in products" :key="i" @click="$set(form,'productId',item.id)">
                {{item.name}}
              </div>
            </div> -->
            <el-radio-group class="category_box" v-model="form.productId">
              <el-radio class="item" v-for="(item,i) in products" :key="i" :label="item.id">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="物品重量" required>
            <div class="printer-num">
              <img @click="reduce()" src="../../static/image/icon_reduce.png" class="reduce" alt="" srcset="" />
              <el-input ref="weight" size="small" class="num" v-model="form.weight" clearable>
                <template slot="append">KG</template>
              </el-input>
              <img @click="add()" src="../../static/image/icon_add.png" class="add" alt="" srcset="" />
            </div>
            <!-- <el-input-number size="small" v-model="form.weight" :min="1" :max="10" label="描述文字">
            </el-input-number> -->
          </el-form-item>
          <el-form-item label="物品价值" required>
            <el-input class="product-amount" ref="productAmount" size="small" v-model="form.productAmount" placeholder="请输入物品价值！" clearable>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="发单时间">
            <el-button @click="form.takeType = 0" :class="!form.takeType ? 'but active' : 'but'" type="info">立即发单</el-button>
            <el-button @click="form.takeType = 1" :class="form.takeType ? 'but but-r active' : 'but'" type="info">预约发单</el-button>
            <el-date-picker @focus="focus" @change="chooseTime" size="small" v-show="form.takeType === 1" v-model="form.takeTime" type="datetime" placeholder="选择日期时间" format="yyyy-MM-dd HH:mm" :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="发单备注">
            <el-input type="text" size="small" v-model="form.takeRemark" maxlength="20" placeholder="请添加备注信息，最多输入20个字！" clearable show-word-limit>
            </el-input>
          </el-form-item>
        </div>
        <div class="moudle">
          <div class="title">
            发票信息
          </div>
          <el-form-item label="发票抬头">
            <el-input size="small" v-model="form.invoiceTitle" placeholder="请输入发票抬头！" clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="发票税号">
            <el-input size="small" v-model="form.taxpayerId" placeholder="请输入发票税号！" clearable>
            </el-input>
          </el-form-item>

        </div>
      </div>

      <!-- 选择门店 -->
      <el-dialog v-loading="loading" element-loading-text="拼命加载中" :title="addressType === 1 ? '选择门店' : '常用地址'" :visible.sync="showChooseShop" width="600px" center>
        <div class="shop-top">
          <div @click="showAddress = true" v-if="addressType === 3 || addressType === 2" class="management-address">地址管理</div>
          <el-input size="small" placeholder="请输入姓名/手机号/地址" v-model="searchKey" @keydown.enter.native="seachEnterFun" clearable>
            <el-button type="primary" @click.stop="getData" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <div class="shop-list">
          <div @dblclick="chooseShop" @click="curIdx = index" :class=" curIdx === index ? 'shop-item active' : 'shop-item'" v-for="(shop,index) in addressList" :key="index">
            <div class="name">{{shop.name}}</div>
            <div class="phone">{{shop.contact + ' ' + shop.phone}}</div>
            <div class="address">{{shop.districtName + shop.address}}</div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="showChooseShop = false">取 消</el-button>
          <el-button size="small" type="primary" @click="chooseShop">确 定</el-button>
        </span>
      </el-dialog>
    </el-form>
    <el-button class="btn" size="small" type="primary" @click="onSubmit">{{form.takeType ? '保存' : '去结算'}}</el-button>
    <!-- 通过地图选择地理位置 -->
    <order-map :key="new Date().getTime()" @getAddressDetail="getAddressDetail" ref="orderMap"></order-map>
    <!-- 发起配送 -->
    <send-order-popup ref="sendOrderPopup"></send-order-popup>
    <!-- 地址管理 -->
    <el-dialog title="常用地址" :visible.sync="showAddress" width="800px" center @close="closeAddress">
      <address-management></address-management>
    </el-dialog>
  </div>

</template>
<script>
import orderMap from "./orderComponents/orderAMap.vue";
import addressManagement from "./addressManagement.vue";
import { getProductList } from "../api/shop.js";
import { getConfig } from "../api/setting.js";
import { sendValuation, saveOrder, getAddressList } from "../api/order.js";
import sendOrderPopup from "../components/orderComponents/sendOrderPopup.vue";
export default {
  name: "manualCreate",
  data() {
    return {
      products: [],
      addressType: 1,
      name: "",
      sendType: this.$store.state.userInfo.memberType === 1 ? 0 : 1,
      memberType: this.$store.state.userInfo.memberType,
      form: {
        name: "",
        sendAddress: {
          id: "",
          address: "",
          cityCode: "",
          cityName: "",
          contact: "",
          lat: "",
          lng: "",
          phone: "",
          provinceName: "",
          districtName: "",
          extension: "",
          street: "",
        },
        receiptAddress: {
          address: "",
          contact: "",
          phone: "",
          street: "",
        },
        weight: 1,
        productId: "",
        takeType: 0,
        takeTime: "",
        takeRemark: "",
        type: this.$store.state.userInfo.memberType === 1 ? 1 : 2,
        isWaimai: false,
        createType: 1,
        shopId: this.$store.state.userInfo.shopId,
        productAmount: 50,
        invoiceTitle: "",
        taxpayerId: "",
        transport: "0",
      },
      chooseMapAddress: 1, // 1 发件选择地址2 收件选择地址
      showChooseShop: false,
      showChooseAddress: false,
      loading: false,
      shopList: [],
      personalList: [],
      addressList: [],
      searchKey: "",
      curIdx: 0,
      isLoading: false,
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() > Date.now() + 3600 * 1000 * 24 ||
            time.getTime() < Date.now() - 3600 * 1000 * 24
          );
        },
      },
      min: 15,
      showAddress: false,
      personalSendAddressId: "",
      personalReceiptAddressId: "",
    };
  },
  components: {
    orderMap,
    sendOrderPopup,
    addressManagement,
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    "$store.state.userInfo": {
      handler(newVal, oldVal) {
        this.sendType = newVal.memberType === 1 ? 0 : 1;
        this.memberType = newVal.memberType;
        this.form.type = newVal.memberType === 1 ? 1 : 2;
        this.form.shopId = newVal.shopId;
      },
      deep: true,
    },
    sendType: {
      handler(newVal, oldVal) {
        this.searchKey = "";
        Object.keys(this.form.sendAddress).map((v) => {
          this.form.sendAddress[v] = "";
        });
        if (newVal) {
          this.addressType = 1;
        } else {
          this.addressType = 2;
        }
        this.getData();
      },
      immediate: true,
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getProductList();
    this.getData();
  },
  // 方法集合
  methods: {
    closeAddress() {
      this.getData();
    },
    seachEnterFun(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        this.getData();
      }
    },
    chooseTime(time) {
      let min = this.min; // 多少分钟后发起配送
      let now = new Date().getTime();
      let inputTime = new Date(time).getTime();
      if (inputTime < now + 60 * 1000 * (min - 1)) {
        this.$message({
          type: "error",
          message: `至少选择${min}分钟后发单！`,
        });
        this.form.takeTime = this.$tool.getFormatDate(now + 60 * 1000 * min);
      } else {
        this.form.takeTime = this.$tool.getFormatDate(inputTime);
      }
    },
    chooseShop() {
      this.showChooseShop = false;
      let sendAddress = this.addressList[this.curIdx];
      if (this.addressType === 1) {
        Object.keys(this.form.sendAddress).map((v) => {
          this.form.sendAddress[v] = sendAddress[v];
        });
        this.name = sendAddress.name;
        this.form.shopId = sendAddress.id;
      } else if (this.addressType === 2) {
        this.form.sendAddress = sendAddress;
        this.personalSendAddressId = sendAddress.id;
      } else {
        this.form.receiptAddress = sendAddress;
        this.personalReceiptAddressId = sendAddress.id;
      }
    },
    showShop(addressType) {
      // 1门店地址发单选择门店 2是个人地址发单选择常用地址 3是收件地址选择常用地址
      this.addressType = addressType;
      this.searchKey = "";
      this.getData();
      this.showChooseShop = true;
    },
    getData() {
      this.loading = true;
      getAddressList({
        searchKey: this.searchKey,
      }).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          let sendAddress;
          if (this.addressType === 1) {
            this.addressList = res.data.shop;
            sendAddress = this.addressList.filter((v) => {
              return v.id === this.form.shopId;
            })[0];
            this.curIdx = this.addressList.findIndex((v) => {
              return v.id === this.form.shopId;
            });
            console.log("sendAddress1", sendAddress);
            Object.keys(this.form.sendAddress).map((v) => {
              this.form.sendAddress[v] = sendAddress ? sendAddress[v] : "";
            });
            this.name = sendAddress ? sendAddress.name : "";
          }
          if (this.addressType === 2) {
            this.addressList = res.data.personal;
            if (this.personalSendAddressId) {
              sendAddress = this.addressList.filter((v) => {
                return v.id === this.personalSendAddressId;
              })[0];
              this.curIdx = this.addressList.findIndex((v) => {
                return v.id === this.personalSendAddressId;
              });
            } else {
              sendAddress = this.addressList.filter((v) => {
                return v.isDefault;
              })[0];
              this.curIdx = this.addressList.findIndex((v) => {
                return v.isDefault;
              });
            }
            console.log("sendAddress2", sendAddress);
            Object.keys(this.form.sendAddress).map((v) => {
              this.form.sendAddress[v] = sendAddress ? sendAddress[v] : "";
            });
          }
          if (this.addressType === 3) {
            this.addressList = res.data.personal;
            let receiptAddress = this.addressList.filter((v) => {
              return v.id === this.personalReceiptAddressId;
            })[0];
            this.curIdx = this.addressList.findIndex((v) => {
              return v.id === this.personalReceiptAddressId;
            });
            console.log("receiptAddress", receiptAddress);
            Object.keys(this.form.receiptAddress).map((v) => {
              this.form.receiptAddress[v] = receiptAddress
                ? receiptAddress[v]
                : "";
            });
          }
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    getProductList() {
      getProductList().then((res) => {
        if (res.code === 200) {
          this.products = res.data;
          this.form.productId = this.products[0].id;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },

    onSubmit() {
      // 去除电话中的空格
      this.form.sendAddress.phone = this.form.sendAddress.phone.replace(
        /\s/g,
        ""
      );
      this.form.receiptAddress.phone = this.form.receiptAddress.phone.replace(
        /\s/g,
        ""
      );
      if (!this.form.sendAddress.phone.trim()) {
        return this.$message({
          type: "error",
          message: "请先输入发件人电话！",
        });
      }
      let reg2 = new RegExp(/^1[3456789]\d{9}$/);
      if (!reg2.test(this.form.sendAddress.phone)) {
        return this.$message({
          type: "error",
          message: "请输入正确的发件人电话!",
        });
      }
      // 个人发件
      if (!this.sendType) {
        this.form.shopId = this.$store.state.userInfo.shopId;
        if (!this.form.sendAddress.contact.trim()) {
          return this.$message({
            type: "error",
            message: "请先输入发件人姓名！",
          });
        }

        if (!this.form.sendAddress.address.trim()) {
          return this.$message({
            type: "error",
            message: "请先选择发件人地址！",
          });
        }
      }
      if (!this.form.receiptAddress.contact.trim()) {
        return this.$message({
          type: "error",
          message: "请先输入收件人姓名！",
        });
      }
      if (!this.form.receiptAddress.phone.trim()) {
        return this.$message({
          type: "error",
          message: "请先输入收件人电话！",
        });
      }
      if (!reg2.test(this.form.receiptAddress.phone)) {
        return this.$message({
          type: "error",
          message: "请输入正确的收件人电话!",
        });
      }
      if (!this.form.receiptAddress.address.trim()) {
        return this.$message({
          type: "error",
          message: "请先选择收件人地址！",
        });
      }
      let reg = new RegExp(/^([1-4][0-9]{0,1}|50)$/);
      if (!reg.test(Number(this.form.weight))) {
        this.$refs.weight.focus();
        return this.$message({
          type: "error",
          message: "物品重量为正整数且不得超过50KG!",
        });
      }
      let reg1 = new RegExp(/(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{2}$)/);
      if (!reg1.test(Number(this.form.productAmount))) {
        this.$refs.productAmount.focus();
        return this.$message({
          type: "error",
          message: "请输入正确的金额!",
        });
      }
      if (Number(this.form.productAmount) > 20000) {
        this.$refs.productAmount.focus();
        return this.$message({
          type: "error",
          message: "物品价值不得超过20000元!",
        });
      }
      // 预约发单
      if (this.form.takeType) {
        if (!this.form.takeTime.trim()) {
          return this.$message({
            type: "error",
            message: "请先选择预约发单时间！",
          });
        }
        let min = this.min; // 多少分钟后发起配送
        let now = new Date().getTime();
        let inputTime = new Date(this.form.takeTime).getTime();
        if (inputTime < now + 60 * 1000 * (min - 1)) {
          return this.$message({
            type: "error",
            message: `预约发单时间至少为${min}分钟后发单！`,
          });
        }
        this.form.saveFlag = 1;
        getConfig().then((res) => {
          if (res.code === 200) {
            let amount = res.data.amount;
            if (amount < 100) {
              this.$confirm(
                "您的账户余额不足100元，可能会导致预约发单失败，请及时充值！",
                "提示",
                {
                  confirmButtonText: "去充值",
                  cancelButtonText: "知道了！",
                  distinguishCancelAndClose: true,
                  center: true,
                  type: "warning",
                }
              )
                .then(() => {
                  this.$router.push({
                    path: "/shopInfo/shopAccount",
                  });
                })
                .catch((action) => {
                  console.log("action:", action);
                  if (action === "close") {
                    return;
                  } else {
                    this.saveOrder();
                  }
                });
            } else {
              this.saveOrder();
            }
          } else {
            this.$message({
              type: "error",
              message: res.msg,
            });
          }
        });
      } else {
        this.form.takeTime = this.$tool.getFormatDate(new Date());
        this.sendValuation();
      }
    },
    saveOrder() {
      saveOrder(this.form).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: "预约单保存成功！",
          });
          this.$router.push({
            name: "HomeIndex",
            params: { tabNum: 1 },
          });
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    // 计价
    sendValuation() {
      this.isLoading = true;
      sendValuation(this.form).then((res) => {
        this.isLoading = false;
        if (res.code == 200) {
          res.data.optionals.forEach((item) => {
            item.optionals = item.optionals ? item.optionals : [];
            item.lowOptionals = item.lowOptionals ? item.lowOptionals : [];
            item.supports = item.supports ? item.supports : [];
          });
          this.$refs.sendOrderPopup.init(res.data, {
            ...this.form,
          });
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    showMap(type) {
      this.searchKey = "";
      this.chooseMapAddress = type;
      if (this.sendType === 1 && this.chooseMapAddress === 1) return;
      this.$refs.orderMap.chooseLocation();
    },
    getAddressDetail(v, lng, lat) {
      let type = "sendAddress";
      if (this.chooseMapAddress === 1) {
        type = "sendAddress";
      } else {
        type = "receiptAddress";
      }
      this.form[type].address = v.address;
      this.form[type].provinceName = v.province;
      this.form[type].cityName = v.city;
      this.form[type].cityCode = v.citycode;
      this.form[type].districtName = v.district;
      this.form[type].lng = lng;
      this.form[type].lat = lat;
    },
    reduce() {
      this.form.weight = this.form.weight === 1 ? 1 : --this.form.weight;
    },
    add() {
      this.form.weight = ++this.form.weight;
    },
    focus() {
      this.$nextTick(() => {
        document
          .getElementsByClassName("el-button--text")[0]
          .setAttribute("style", "display:none"); // 隐藏此刻按钮
      });
    },
  },
};
</script>

<style lang="scss" scoped="scoped">
.form-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: calc(100% - 40px);
  padding: 20px;
  background: #fff;
  .product-amount {
    width: 190px;
  }
  .moudle-list {
    display: flex;
    flex-wrap: wrap;
    .moudle {
      width: 600px;
      margin: 0 100px 50px 0;
      /deep/ .el-radio__input.is-checked .el-radio__inner {
        border-color: #fc7200;
        background: #fc7200;
      }
      /deep/ .el-radio__input.is-checked + .el-radio__label {
        color: #fc7200;
      }
      .category_box {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        margin-top: -10px;

        .item {
          display: flex;
          align-items: center;
          width: 92px;
          height: 30px;
          margin: 10px 10px 0 0;
          border-radius: 2px;
          cursor: pointer;

          &.active {
            color: #ffffff;
            background: #fc7200;
            border-color: #fc7200 !important;
          }
        }
      }
      .phone-before {
        width: 50%;
      }
      .phone-center {
        margin: 0 15px;
      }
      .phone-after {
        width: 70px;
      }
      .map {
        height: 25px;
        width: 25px;
        cursor: pointer;
      }
    }
  }
  .btn {
    width: 200px;
    height: 40px;
    font-size: 14px;
    background: #fc7200;
    border: #fc7200;
    margin-top: -50px;
  }
  /deep/ .el-form {
    display: flex;
    flex-wrap: wrap;
  }
  /deep/ .el-form-item__label {
    color: #b1b1b1;
  }
  .title-list {
    display: flex;
    align-items: center;
    .normal-title {
      color: #999;
      font-weight: bold;
      margin: 0 30px 20px 0;
      cursor: pointer;
    }
    .normal-title:before {
      content: "";
      display: inline-block;
      width: 3px;
      height: 14px;
      background-color: #999;
    }
  }
  .title {
    font-weight: bold;
    color: #333;
    margin: 0 30px 20px 0;
    cursor: pointer;
  }
  .title:before {
    content: "";
    display: inline-block;
    width: 3px;
    height: 14px;
    background-color: #fc7200;
  }
  .but {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0;
    border-radius: 0;
    height: 32px;
    background: #ebebeb;
    border-color: #ebebeb;
    color: #666;
    &.active {
      color: #ffffff;
      background: #fc7200;
      border-color: #fc7200 !important;
    }
    &.but-r {
      margin-right: 20px;
    }
  }
  .but1 {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 100px;
    height: 32px;
    &.active {
      color: #ffffff;
      background: #fc7200;
      border-color: #fc7200 !important;
    }
  }
  /deep/ .el-form-item__content {
    display: flex;
    align-items: center;
    line-height: 32px;
  }
  .printer-num {
    display: flex;
    align-items: center;
    .reduce {
      width: 32px;
      height: 32px;
      cursor: pointer;
    }
    .num {
      margin: 0 10px;
      width: 150px;
    }
    .add {
      width: 32px;
      height: 32px;
      cursor: pointer;
    }
    .name {
      margin-left: 20px;
    }
  }
  .shop-top {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .management-address {
      flex-shrink: 0;
      color: #fc7200;
      margin-right: 15px;
      cursor: pointer;
    }
  }
  .shop-list {
    height: 60vh;
    overflow: scroll;
    .shop-item {
      border: 1px solid #999;
      padding: 10px;
      margin: 10px 0;
      border-radius: 5px;
      color: #333;
      cursor: pointer;
    }
    .active {
      border-color: #fc7200;
      color: #fc7200;
    }
  }
}
</style>