<template>
  <el-dialog
    :title="'项目下单'"
    :center="true"
    align="left"
    top="5vh"
    width="1040px"
    @close="showModelThis = false"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    append-to-body
  >
    <el-card style="margin-top: -20px">
      <el-row>
        <el-col :span="24">
          <show-data-table
            style="margin: 0; padding: 0"
            border
            :newTime="newTime"
            v-if="newTime !== '' && sitem"
            :sitem="sitem"
            :columns="ShowDataTableColumns"
          />
        </el-col>
        <el-col :span="24" style="padding: 10px 0 0 0">
          <span style="line-height: 30px">商品下单：</span>
          <el-button-group :size="'mini'" class="fr" style="margin: 0 0 8px 0">
            <el-button
              class="fr"
              type="primary"
              :size="'mini'"
              :disabled="index === 0"
              v-if="total !== 0"
              icon="el-icon-arrow-left"
              @click="prev_goods()"
            ></el-button>
            <el-button
              type="primary"
              class="fr"
              v-if="total !== 0"
              :size="'mini'"
              style="height: 29px"
              >商品共{{ index + 1 }}/{{ total }}</el-button
            >
            <el-button
              type="primary"
              class="fr"
              v-if="total !== 0"
              @click="next_goods()"
              :size="'mini'"
              ><i class="el-icon-arrow-right el-icon--right" :size="'mini'"></i
            ></el-button>
          </el-button-group>
        </el-col>
        <el-col :span="24">
          <el-table
            :data="order_good"
            border
            :size="'mini'"
            style="width: 100%"
            row-key="key"
          >
            <el-table-column
              prop="good_img"
              label="商品图片"
              min-width="242px"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <div v-if="scope.row.good_img && scope.row.good_img.length > 0">
                  <img
                    v-for="(si, sii) in scope.row.good_img"
                    :key="si + sii"
                    :src="si"
                    class="hover fl"
                    style="
                      display: inline-block;
                      width: 20px;
                      height: 20px;
                      margin: 0 2px 0 0;
                    "
                    alt=""
                    v-viewer
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="good_name"
              label="商品名称"
              show-overflow-tooltip
              min-width="120"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.good_name }}</span>
                <span v-for="(si, sii) in scope.row.specinfo" :key="si.id + sii">
                  {{ sii === 0 ? "_" : "-" }}{{ si.spec_name }}[{{ si.spec_value_name }}]
                </span>
              </template>
            </el-table-column>

            <el-table-column
              prop="brand_name"
              label="品牌"
              width="110"
              show-overflow-tooltip
            />
            <el-table-column
              prop="sale_price"
              label="单价"
              width="110"
              show-overflow-tooltip
            />
            <el-table-column prop="num" label="数量" width="100" show-overflow-tooltip />
            <el-table-column
              prop="sendtype"
              label="发货方式"
              width="150"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.sendtype"
                  placeholder="发货方式"
                  :size="'mini'"
                  @change="sendtype_change($event, scope.$index)"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="24" v-if="sendtype === '1'" style="padding: 15px 0 0 0">
          <el-form :model="addrForm" ref="addrForm" :size="'mini'">
            <el-table
              :data="addrForm.order_addr"
              border
              :size="'mini'"
              style="width: 100%"
              max-height="300px"
              row-key="key"
            >
              <el-table-column type="index" width="80" show-overflow-tooltip />
              <el-table-column
                prop="receipt_quantity"
                label="收货总数"
                min-width="125"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-form-item
                    v-if="scope.row.edit"
                    :prop="'order_addr.' + scope.$index + '.' + 'receipt_quantity'"
                    :rules="addrRules.receipt_quantity"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <el-input
                      v-model="scope.row.receipt_quantity"
                      :disabled="!scope.row.edit"
                      maxlength="10"
                    />
                  </el-form-item>
                  <span v-if="!scope.row.edit">{{ scope.row.receipt_quantity }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="contactor"
                label="收件联系人"
                min-width="110"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-form-item
                    v-if="scope.row.edit"
                    :prop="'order_addr.' + scope.$index + '.' + 'contactor'"
                    :rules="addrRules.contactor"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <el-input
                      v-model="scope.row.contactor"
                      :disabled="!scope.row.edit"
                      maxlength="20"
                    />
                  </el-form-item>
                  <span v-if="!scope.row.edit">{{ scope.row.contactor }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="mobile"
                label="收货联系电话"
                min-width="130"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-form-item
                    v-if="scope.row.edit"
                    :prop="'order_addr.' + scope.$index + '.' + 'mobile'"
                    :rules="addrRules.mobile"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <el-input
                      v-model="scope.row.mobile"
                      :disabled="!scope.row.edit"
                      maxlength="11"
                    />
                  </el-form-item>
                  <span v-if="!scope.row.edit">{{ scope.row.mobile }}</span>
                </template>
              </el-table-column>

              <el-table-column
                prop="addr_code"
                label="收货省市区"
                min-width="230"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-form-item
                    v-if="scope.row.edit"
                    :prop="'order_addr.' + scope.$index + '.' + 'addr_code'"
                    :rules="addrRules.addr_code"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <select-area
                      :value="scope.row.addr_code"
                      :disabled="!scope.row.edit"
                      :size="'mini'"
                      @selectChange="select_area_change($event, scope.$index)"
                    />
                  </el-form-item>
                  <span v-if="!scope.row.edit">{{ scope.row.addr_code_name }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="addr"
                label="详细地址"
                min-width="170"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-form-item
                    v-if="scope.row.edit"
                    :prop="'order_addr.' + scope.$index + '.' + 'addr'"
                    :rules="addrRules.addr"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <el-input
                      v-model="scope.row.addr"
                      :disabled="!scope.row.edit"
                      maxlength="100"
                    />
                  </el-form-item>
                  <span v-if="!scope.row.edit">{{ scope.row.addr }}</span>
                </template>
              </el-table-column>

              <el-table-column fixed="right" width="94" show-overflow-tooltip>
                <template slot="header" slot-scope="scope">
                  <el-tooltip
                    class="fr"
                    style="margin: 3px 0 0 8px"
                    effect="dark"
                    content="手动添加地址"
                    placement="top"
                  >
                    <i
                      class="el-icon-circle-plus-outline tb-icon"
                      style="color: #6954f0"
                      @click="openHouseModal(-1)"
                    ></i>
                  </el-tooltip>
                  <el-tooltip
                    class="fr"
                    style="margin: 3px 0 0 8px"
                    effect="dark"
                    content="导入收货地址"
                    placement="top"
                  >
                    <i
                      class="el-icon-upload2 tb-icon"
                      style="color: #6954f0"
                      @click="addrmodel = true"
                    ></i>
                  </el-tooltip>
                  <el-tooltip
                    class="fr"
                    style="margin: 3px 0 0 0"
                    effect="dark"
                    content="下载收货地址模板"
                    placement="top"
                  >
                    <a class="downloadAddr" href="./static/收货地址模板.xlsx">
                      <i
                        class="el-icon-download tb-icon"
                        style="color: #6954f0; margin: 0"
                      ></i>
                    </a>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-tooltip
                    effect="dark"
                    content="编辑"
                    v-if="!scope.row.edit"
                    placement="top"
                  >
                    <i
                      class="el-icon-edit tb-icon"
                      @click="openHouseModal(scope.$index)"
                    ></i>
                  </el-tooltip>

                  <el-tooltip
                    effect="dark"
                    content="保存"
                    v-if="scope.row.edit"
                    placement="top"
                  >
                    <i
                      class="el-icon-circle-check tb-icon"
                      @click="checkRow(scope.$index)"
                    ></i>
                  </el-tooltip>

                  <el-tooltip effect="dark" content="删除" placement="top">
                    <i
                      class="el-icon-delete tb-icon"
                      @click="deleteRow(scope.$index, addrForm.order_addr)"
                    ></i>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-col>
        <el-col :span="24">
          <in-addr-model
            :show-model="addrmodel"
            @cancel="addrmodel = false"
            @refresh="addrRefresh"
          />
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/sellOut/project";
import searchStockGoodModal from "@/components/search-stock-good-modal";
import {
  isnumber,
  isMobile,
  isChinese,
  isEmoticon,
  isSpecialSymbol,
  hasSpace,
  isAddr,
} from "@/utils/validate";
import inAddrModel from "@/components/in-addr-model";
import { ShowDataTableColumns } from "./ShowDataTableColumns";
export default {
  name: "buyGoodModal",
  props: ["showModel", "sitem"],
  mixins: [resToken],
  components: { searchStockGoodModal, inAddrModel },
  data() {
    const validatemobile = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号不能为空！"));
      } else {
        if (!isMobile(value)) {
          callback(new Error("手机号格式不正确！"));
        } else {
          callback();
        }
      }
    };
    const validateWeight = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("收货总数不能为空!"));
      } else {
        if (!isnumber(value)) {
          callback(new Error("收货总数仅支持整数!"));
        } else {
          callback();
        }
      }
    };
    const validatecontactor = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("联系人不能为空！"));
      } else {
        if (value.length < 2 || value.length > 10) {
          callback(new Error("联系人规则为2~10位汉字！"));
        } else {
          if (!isChinese(value)) {
            callback(new Error("联系人规则为2~10位汉字！"));
          } else if (isEmoticon(value)) {
            callback(new Error("联系人规则为2~10位汉字！"));
          } else {
            callback();
          }
        }
      }
    };
    const validateAddr = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("详细地址不能为空！"));
      } else {
        if (hasSpace(value)) {
          callback(new Error("不能出现/回车/换行符！"));
        } else if (isSpecialSymbol(value)) {
          callback(new Error("不能使用英文特殊字符！"));
        } else if (isAddr(value)) {
          callback();
        } else {
          callback(new Error("详细地址填写不规范！"));
        }
      }
    };
    return {
      loading: false,
      addrmodel: false,
      showModelThis: this.showModel,
      showGoodsModel: false,
      ShowDataTableColumns: ShowDataTableColumns,
      planNo: "",
      arrtime: "",
      project_list: [],
      options: [
        {
          value: "1",
          label: "直接发货",
        },
        {
          value: "2",
          label: "延时发货",
        },
      ],
      index: 0,
      total: 0,
      order_good: [],
      sendtype: "1",
      addrForm: {
        order_addr: [], //收货地址
      },
      addrRules: {
        receipt_quantity: [
          {
            required: true,
            validator: validateWeight,
            trigger: "blur",
          },
        ],

        contactor: [
          {
            required: true,
            trigger: "blur",
            validator: validatecontactor,
          },
        ],
        mobile: [
          {
            required: true,
            validator: validatemobile,
            trigger: "blur",
          },
        ],

        addr_code: [
          {
            type: "array",
            required: false,
            trigger: "change",
          },
        ],
        addr: [
          {
            required: true,
            validator: validateAddr,
            trigger: "blur",
          },
        ],
      },

      loading: false,
      id: "",
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    closeModel() {
      console.log("closeModel!!");
      this.showModelThis = false;
    },

    async initForm() {
      this.loading = true;
      this.project_list = [];
      console.log(this.sitem);
      const { planNo, in_arrival_time, feedback } = this.sitem;
      this.planNo = planNo || "";
      this.arrtime = in_arrival_time || "";
      let goods = JSON.parse(JSON.stringify(feedback));
      if (goods && goods.length > 0) {
        goods.forEach((e) => {
          e.sendtype = "1";
          let model = JSON.parse(JSON.stringify(e));
          let item = {
            order_good: [model],
            order_addr: [],
          };
          this.project_list.push(item);
        });
      }
      this.index = 0;
      this.total = this.project_list.length;
      await this.resetForm(this.index);
      this.getNewTime();
      this.loading = false;
    },
    addrRefresh(e) {
      const { list } = e;
      this.addrForm.order_addr.push(...list);
    },
    async prev_goods() {
      this.index--;
      await this.resetForm(this.index);
    },
    async next_goods() {
      const { order_addr } = this.addrForm;
      const { num } = this.order_good[0];
      let ta = 0;
      if (this.sendtype === "1" && order_addr && order_addr.length === 0) {
        this.$message.warning("直接发货需要录入地址！");
        return;
      }
      let isedit = false;
      order_addr.forEach((e) => {
        ta += e.receipt_quantity * 1;
        if (e.edit) {
          isedit = true;
        }
      });
      if (isedit) {
        this.$message.warning("当前已有地址在编辑，请保存后再试！");
        return;
      }
      if (this.sendtype === "1" && ta !== parseInt(num + "")) {
        this.$message.warning("收货数量总数与购买数量总数不一致！");
        return;
      }

      this.project_list[this.index].order_good[0].sendtype = this.sendtype;
      this.project_list[this.index].order_addr =
        this.addrForm.order_addr.length === 0
          ? []
          : JSON.parse(JSON.stringify(this.addrForm.order_addr));
      if (this.index + 1 === this.total) {
        this.submitForm();
      } else {
        this.index++;

        await this.resetForm(this.index);
      }
    },

    getNewTime() {
      this.newTime = new Date().valueOf();
    },
    sendtype_change(e, index) {
      this.order_good[index].sendtype = e;
      this.sendtype = this.order_good[index].sendtype;
    },

    async resetForm(index) {
      //重置
      await this.$nextTick(() => {
        if (this.$refs.addrForm) {
          this.$refs.addrForm.resetFields();
          this.$refs.addrForm.clearValidate();
        }
        let list1 = this.project_list[index].order_good;
        this.order_good = list1.length > 0 ? JSON.parse(JSON.stringify(list1)) : [];

        this.order_good[0].good_img = this.order_good[0].good_img.split(",");
        let list2 = this.project_list[index].order_addr;
        this.addrForm.order_addr =
          list2.length > 0 ? JSON.parse(JSON.stringify(list2)) : [];
        this.sendtype = this.order_good[0].sendtype;
      });
    },
    openHouseModal(index) {
      let findex = this.addrForm.order_addr.findIndex((v) => v.edit === true);
      if (findex !== -1) {
        this.$message.warning("当前已有地址在编辑，请保存后再试！");
        return;
      } else {
        if (index === -1) {
          this.addrForm.order_addr.push({
            edit: true,
            receipt_quantity: "",
            contactor: "",
            mobile: "",
            addr_code: [],
            addr: "",
          });
        } else {
          this.addrForm.order_addr[index].edit = true;
        }
      }
    },
    //省市区选择
    async select_area_change(e, index) {
      this.addrForm.order_addr[index].addr_code = e;
      const { addr_code } = this.addrForm.order_addr[index];
      if (addr_code && addr_code.length === 3) {
        let arrCode = addr_code[addr_code.length - 1];
        // console.log(model);
        let { code, data, message } = await asyncRequest.addrall({
          code: arrCode,
        });
        if (code === 0) {
          const { province, city, area } = data;
          let province_name = province && province.name ? province.name : "";
          let city_name = city && city.name ? city.name : "";
          let area_name = area && area.name ? area.name : "";
          this.addrForm.order_addr[index].addr_code_name =
            province_name && city_name && area_name
              ? `${province_name}/${city_name}/${area_name}`
              : "";
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(message);
        }
      } else {
        this.addrForm.order_addr[index].addr_code_name = "";
      }
    },
    //省市区保存某一行
    checkRow(rowIndex) {
      this.$refs.addrForm.validate((valid) => {
        if (valid) {
          this.addrForm.order_addr[rowIndex].edit = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 省市区删除行操作
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    async submitForm() {
      if (this.loading) {
        return;
      }
      this.loading = true;
      let model = {
        planNo: this.planNo,
        arrtime: this.arrtime,
        planinfo: [],
      };
      this.project_list.forEach((e) => {
        const { order_good, order_addr } = e;

        const { id, sendtype } = JSON.parse(JSON.stringify(order_good[0]));
        let modelA = {
          feedback_id: id || "",
          sendtype: sendtype || "2",
          addrlist: [],
        };
        order_addr.forEach((a) => {
          let modelB = {
            addr_code: a.addr_code.toString(),
            contactor: a.contactor,
            mobile: a.mobile,
            addr: a.addr,
            receipt_quantity: a.receipt_quantity,
          };
          modelA.addrlist.push(modelB);
        });
        model.planinfo.push(modelA);
      });
      let res = await asyncRequest.project_place_order(model);
      this.loading = false;
      if (res && res.code === 0) {
        this.$notify.success({
          title: "下单成功！",
          message: "",
        });
        this.showModelThis = false;
        // 刷新
        this.$emit("refresh");
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
// .capitalClaim {
.excelUploadBox {
  position: relative;
  width: 100%;
  height: 120px;
  line-height: 120px;
  box-sizing: border-box;
  &:hover {
    cursor: pointer;
  }
  .el-icon-receiving {
    width: 100%;
    text-align: center;
    height: 50px;
    display: block;
    font-size: 32px;
    line-height: 90px;
    color: #d3d4d6;
  }
  .boxM {
    width: 100%;
    display: block;
    text-align: center;
    line-height: 65px;
    height: 60px;
    color: #909399;
  }
}
.excelUpload {
  top: 0;
  left: 0;
  position: absolute;
  z-index: 2;
  width: 100%;
  height: 120px;
  line-height: 120px;
  box-sizing: border-box;
}
.excelUploadRes {
  width: 100%;
  height: 120px;
  line-height: 120px;
  box-sizing: border-box;
  i {
    width: 55px;
    height: 120px;
    line-height: 120px;
    text-align: center;
    font-size: 20px;
    &.fl {
      padding-left: 16px;
    }
    &.fr {
      padding-right: 16px;
      &:hover {
        cursor: pointer;
      }
    }
  }
  span {
    width: 386px;
    line-height: 16px;
    margin: 52px 0 0 0;
    font-size: 16px;
  }
}
// }
</style>
