<template>
  <div class="salesOrderDetail">
    <el-row>
      <el-col :span="24">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          status-icon
          :size="'mini'"
          :rules="rulesThis"
          label-width="95px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="业务公司" prop="companyNo">
                <search-work-company
                  :type="'1'"
                  :size="'mini'"
                  :disabled="true"
                  :isDetail="false"
                  :placeholder="'业务公司'"
                  :value="ruleForm.companyNo"
                  @searchChange="supplierChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业客户" prop="customer_code">
                <search-customer
                  :value="ruleForm.customer_code"
                  :size="'mini'"
                  :names="companyName"
                  :placeholder="'企业客户'"
                  :disabled="false"
                  :is-detail="true"
                  @searchChange="customer_code_change"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属平台" prop="platform_id"  style="margin-bottom: 16px;">
                <search-terrace
                  :value="ruleForm.platform_id"
                  :disabled="false"
                  :size="'mini'"
                  :is_show="'1'"
                  :isDetail="false"
                  :placeholder="'所属平台'"
                  @searchChange="platform_idsearchChange"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
                <el-form-item label="销售数量" prop="good_num">
                  <digital-input
                    :values="ruleForm.good_num"
                    :name="'ruleForm.good_num'"
                    :placeholder="'销售数量'"
                    :disabled="!ruleForm.good_code"
                    :min="0"
                    :max="100000000000"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :controls="false"
                    :append="''"
                    @reschange="number_change($event, 'good_num')"
                  />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <!-- ruleForm.good_price + '' === '0' -->
                <el-form-item label="销售单价" prop="new_good_price">
                  <digital-input
                    :values="ruleForm.new_good_price"
                    :placeholder="'销售数量'"
                    :min="ruleForm.good_price || 0"
                    :disabled="true"
                    :position="'right'"
                    :precision="2"
                    :size="'mini'"
                    :controls="false"
                    :append="''"
                    @reschange="number_change($event, 'new_good_price')"
                  />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                :label="ruleForm.good_code === '' ? '销售商品' : ''"
                prop="good_code"
                :label-width="ruleForm.good_code === '' ? '95px' : '0'"
              >
                <el-input
                  v-if="ruleForm.good_code === ''"
                  v-model="ruleForm.good_code"
                  placeholder="请选择商品"
                  readonly
                  maxlength="200"
                  @focus="change_good_code"
                />
                <show-data-table
                  v-else
                  border
                  style="margin: 0; padding: 0"
                  :sitem="goods_sitem"
                  :columns="ShowDataTableColumns"
                >
                  <template slot="good_name">
                    <img
                      v-viewer
                      style="width: 23px; height: 23px; margin: 0 5px 0 0"
                      class="fl"
                      v-if="goods_sitem.good_thumb_img"
                      :src="goods_sitem.good_thumb_img"
                      alt
                    />
                    <span>{{ goods_sitem.good_name }}</span>
                    <span v-for="(si, i) in goods_sitem.specinfo" :key="si.spec_id + i">
                      <span>{{ i === 0 ? "--" : "__" }}</span>
                      <span>{{ si.spec_name }}[{{ si.spec_value }}]</span>
                    </span>
                  </template>
                  <template slot="good_info_img">
                    <img
                      class="fl"
                      style="width: 23px; height: 23px; margin: 0 5px 0 0"
                      v-viewer
                      v-for="(si, i) in goods_sitem.good_info_img"
                      :src="si"
                      :key="si + i"
                    />
                  </template>
                  <template slot="cat">
                    <span v-for="(si, sii) in goods_sitem.cat_info" :key="si.id">
                      <span v-if="sii !== 0">_</span>
                      <span>{{ si.name }}</span>
                    </span>
                  </template>
                  <template slot="exclusive">
                    <span v-for="(si, sii) in goods_sitem.exclusive" :key="si.id">
                      <span v-if="sii !== 0">/</span>
                      <span>{{ si.name }}</span>
                    </span>
                  </template>
                  <template slot="is_stock">
                    <el-tag :size="'mini'">
                      {{
                      goods_sitem.is_stock + "" === "1" ? "是" : "否"
                      }}
                    </el-tag>
                  </template>
                  <template slot="weight">
                    <span>
                      商品总重：{{ goods_sitem.new_weight }}/{{
                      goods_sitem.weight_unit
                      }}
                    </span>
                    <span v-if="goods_sitem.metal_id">
                      --{{
                      goods_sitem.noble_weight ? goods_sitem.noble_weight : "0"
                      }}g--{{ goods_sitem.metal_name }}---{{
                      goods_sitem.gold_price ? goods_sitem.gold_price : "0"
                      }}元/g--{{
                      goods_sitem.is_gold_price + "" === "0" ? "不" : ""
                      }}启用实时金价--{{
                      goods_sitem.is_diff + "" === "1" ? "有" : "无"
                      }}工差--{{ goods_sitem.config }}---{{
                      goods_sitem.other_config }}
                    </span>
                  </template>
                </show-data-table>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="剩余库存">
                    <el-input
                      v-model="ruleForm.activity_stock"
                      disabled
                      maxlength="200"
                      placeholder="剩余库存"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="系统最低售价" prop="good_price" label-width="110px">
                    <el-input
                      v-model="ruleForm.good_price"
                      disabled
                      maxlength="20"
                      v-loading="priceLoding"
                    >
                      <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>

            <el-col :span="12">
              <el-form-item label="业务经理" prop="managerid">
                <project-manager
                  size="mini"
                  :isDetail="true"
                  :value="ruleForm.managerid"
                  @searchChange="manageridChange"
                />
              </el-form-item>
            </el-col>

            <!-- <el-col :span="6">
              <el-form-item label="到货时间" prop="arrtime">
                <el-date-picker
                  v-model="ruleForm.arrtime"
                  type="date"
                  style="width: 100%"
                  :disabled="false"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  placeholder="要求到货时间"
                ></el-date-picker>
              </el-form-item>
            </el-col> -->

            <!-- <el-col :span="6">
              <el-form-item label="下单方式" prop="sendtype">
                <el-select v-model="ruleForm.sendtype" placeholder="下单方式" style="width: 100%">
                  <el-option
                    v-for="item in sendtype_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item> -->
            <!-- </el-col> -->

            <el-col :span="ruleForm.good_code ? 12 : 24">
              <el-form-item label="订单备注" prop="remark">
                <el-input
                  type="textarea"
                  maxlength="250"
                  show-word-limit
                  :rows="ruleForm.good_code ? 4 : 2"
                  placeholder="订单备注"
                  v-model="ruleForm.remark"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <search-good-online-modal
                :once="true"
                :sitem="addshowModel"
                is_combind="0"
                :active="true"
                :show-model="showModel"
                :platform_type="platformType"
                @resultList="resultList"
                @cancel="showModel = false"
              />
            </el-col>
          </el-row>
        </el-form>
      </el-col>
      <el-col :span="24">
        <in-addr-model :show-model="addrmodel" @cancel="addrmodel = false" @refresh="addrRefresh" />

        <show-voucher-model
          :showModel="showVoucher"
          :id="goods_sitem.spuCode"
          @cancel="showVoucher = false"
          @searchChange="resvoucher"
        />
      </el-col>
      <el-col
        :span="24"
        style="
          display: flex;
          text-align: right;
          padding: 0 0 20px 0;
          justify-content: flex-end;
        "
      >
        <el-button :size="'mini'" type="primary" @click="submitForm">保 存</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/sellOut/businessFiling";
import showVoucherModel from "@/components/show-voucher-model";
import searchGoodOnlineModal from "@/components/good-online-platform-modal";
import inAddrModel from "@/components/in-addr-model";
import { addColumns } from "./ShowDataTableColumns";
import companyHelper from "@/mixins/companyHelper";
import { replaceTextWrapAndSpace } from "@/utils";
import { accMul } from "@/utils/validate";
import { mapGetters } from "vuex";

import {
  isnumber,
  isMobile,
  isChinese,
  isEmoticon,
  isSpecialSymbol,
  hasSpace,
  isAddr
} from "@/utils/validate";

export default {
  name: "salesOrderDetail",
  mixins: [mixinPage, resToken, companyHelper],
  props: ["newTime", "id", "sitem", "type"],
  computed: {
    ...mapGetters(["business_companyNo"])
  },
  components: {
    inAddrModel,
    showVoucherModel,
    searchGoodOnlineModal
  },
  watch: {
    newTime: function(val) {
      if (val) { this.initForm(); }
    }
  },
  data() {
    return {
      isCombindChild: true,
      ShowDataTableColumns: addColumns,
      AddrAddEditModalIndex: -1,
      AddrAddEditModalSitem: {},
      showGoodsModel: false,
      showVoucher: false,
      companyName: "",
      showModel: false,
      addrmodel: false,
      addshowModel: {},
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
        }
      },
      platformType:"",
      ruleForm: {
        order_type: "1",
        supplierNo: "", //销售方编码
        customer_code: [], // 企业客户选择
        platform_id: "",
        new_good_price: "0",
        activity_stock: "0",
        is_activity: "0", //是否参与活动,
        goodtype: ["is_activity_0", "1"], //活动类型
        good_num: "0", //商品数量
        good_price: 0, //商品单价
        remark: "", //备注
        good_code: "", // 商品编号
        managerid: []
      },
      rulesThis: this.rules,
      rules: {
        managerid: [
          {
            required: true,
            message: "请选择业务经理",
            trigger: "change"
          }
        ],
        companyNo: [
          {
            required: true,
            message: "请选择业务公司",
            trigger: "change"
          }
        ],
        customer_code: [
          {
            type: "array",
            required: true,
            message: "请选择企业客户",
            trigger: "change"
          }
        ],
        platform_id: [
          {
            required: true,
            message: "请选择所属平台",
            trigger: "change"
          }
        ],
        new_good_price: [
          {
            required: true,
            message: "销售单价不能为空！",
            trigger: "blur"
          }
        ],
        good_num: [
          {
            required: true,
            message: "请选择活动类型",
            trigger: "change"
          }
        ],
        good_code: [
          {
            required: true,
            message: "请选择销售商品",
            trigger: "blur"
          }
        ],
        remark: [
          {
            required: true,
            message: "备注不能为空",
            trigger: "blur"
          }
        ]
      },
      addrForm: {
        order_addr: [] //收货地址
      },
      delAddrList: [],
      delStockList: [],
      loading: false,
      queryId: "",
      status: "",
      goods_sitem: {},
      order_good_num: {
        ogood_type: "",
        ogood_num: "0"
      },
      priceLoding: false
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    manageridChange(e) {
      const { id, label } = e;
      this.ruleForm.managerid = id ? [id] : [];
      this.ruleForm.manager = label || "";
    },
    priceAccMul(a, b) {
      return accMul(a, b);
    },
    async initForm() {
      this.status = "";
      this.queryId = this.$route.query.id;
      this.rulesThis = this.rules;
      this.resetForm();
    },

    getNewTime() {
      this.newTime = new Date().valueOf();
    },

    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();

          this.ruleForm = {
            managerid: [],
            manager:"",
            order_type: "1",
            companyNo: this.currentCompany || "", //销售方编码
            customer_code: [], // 企业客户选择
            platform_id: "",
            new_good_price: "",
            activity_stock: "0",
            goodtype: ["is_activity_0", "1"], //活动类型
            good_num: "0", //商品数量
            good_price: 0, //系统商品单价
            remark: "", //备注
            good_code: "" // 商品编号
          };
        }

        if (this.$refs.addrForm) {
          this.$refs.addrForm.resetFields();
          this.$refs.addrForm.clearValidate();
          const { addrs } = this.sitem;
          this.addrForm = {
            order_addr: []
          };
          this.delAddrList = [];

          if (addrs && addrs.length > 0) {
            addrs.forEach(v => {
              const { area_code, city_code, provice_code } = v.addr_code;
              let model = {
                edit: false,
                receipt_quantity: v.receipt_quantity || "",
                contactor: v.contactor || "",
                mobile: v.mobile || "",
                addr_code:
                  area_code && city_code && provie_code
                    ? [provice_code, city_code, area_code]
                    : [],
                addr: v.addr || "",
                id: v.id,
                is_del: 0
              };
              this.delAddrList.push(model);
              this.addrForm.order_addr.push(model);
            });
          }
        }
      });
    },
    addrRefresh(e) {
      const list = JSON.parse(JSON.stringify(e.list));
      list.forEach(item => {
        item.code = item.areaCode ? [item.areaCode] : [];
        item.names = item.label ? [item.label] : [];
      });
      this.addrForm.order_addr.push(...list);
    },
    async resultList(e) {
      this.showModel = false;
      if (e.length === 1) {
        let ssitem = JSON.parse(JSON.stringify(e[0]));
        const result = await this.get_goods_detail(ssitem.skuCode);
        this.ruleForm.good_code = this.goods_sitem.skuCode;
      } else {
        this.goods_sitem = {};
        this.ruleForm.good_code = "";
      }
      this.$refs.ruleForm.validateField("good_code");
    },
    async get_goods_detail(skuCode) {
      let { code, data, message } = await asyncRequest.goods_detail({
        skuCode: skuCode
      });
      if (code === 0) {
          const { is_combind_child } = data;
          this.isCombindChild = is_combind_child === false;
        this.goods_sitem = data;
        this.goods_sitem.good_info_img = this.goods_sitem.good_info_img.split(
          ","
        );

        const { weight } = this.goods_sitem;
        let kgnum = parseInt((weight * 1) / 1000);
        let gnum = (weight * 1) % 1000;
        let new_weight,
          weight_unit = "";
        if (kgnum > 0) {
          weight_unit = "Kg";
          new_weight = `${kgnum}.${gnum}`;
        } else {
          new_weight = weight;
          weight_unit = "g";
        }

        this.goods_sitem.new_weight = new_weight;
        this.goods_sitem.weight_unit = weight_unit;
        this.ruleForm.good_code = this.goods_sitem.good_code;
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    showVoucherFun() {
      if (this.goods_sitem && this.goods_sitem.spuCode) {
        this.showVoucher = true;
      } else {
        this.$message.warning("请选择商品！");
        return;
      }
    },
    async addGoodsRes(e) {
      if (e && e.length === 1) {
        this.ruleForm.good_name = e[0].good_name;
        this.ruleForm.good_code = e[0].type_code;
      } else {
        this.ruleForm.good_name = "";
        this.ruleForm.good_code = "";
      }
      this.$refs.ruleForm.validateField("good_code");
      if (this.ruleForm.good_code !== "" && this.queryId === "add") {
      } else {
      }
    },
    async number_change(e, key) {
      this.ruleForm[key] = e + "" || "0";
      const { good_num } = this.ruleForm;

      if (Number(good_num ?? "0") !== 0) {
        await this.get_new_price();
      }

      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.validateField(key);
      }
    },
    async get_new_price() {
      const { good_num } = this.ruleForm;

      if (!this.priceLoding) {
        const { isok, price, stock } = await this.set_salegetprice();

        console.log("商品:" , price, stock)
        this.ruleForm.good_price = isok ? price : 0;
        this.ruleForm.activity_stock = isok ? stock : 0;
      }
    },
    change_good_code() {
      const { supplierNo, platform_id } = this.ruleForm;
      if (supplierNo === "") {
        this.$message.warning("请选择销售方公司！");
        return;
      }
      
      if (platform_id === "") {
        this.$message.warning("请选择所属平台！");
        return;
      }

      if(this.platformType === "1"){
        this.$message.warning("当前业务不支持对接有赞平台的商品")
        return
      }

      if(this.platformType === "2"){
        this.$message.warning("当前业务不支持对接BBC平台的商品")
        return
      }

      this.addshowModel = {
        company_id: supplierNo,
        platform_code: platform_id
      };
      this.showModel = true;
    },
    customer_code_change(e) {
      if (e && e.code) {
        this.ruleForm.customer_code = [e.code];
      } else {
        this.ruleForm.customer_code = [];
      }
      this.$refs.ruleForm.validateField("customer_code");
    },
    supplierChange(e) {
      const { id, code, label } = e;
      this.ruleForm.companyNo = code || "";
      this.$refs.ruleForm.validateField("supplierNo");
      this.ruleForm.proof_id = "";
      this.ruleForm.proof_url = "";
      this.ruleForm.proof_type = "";
      this.$refs.ruleForm.validateField("proof_id");
      this.ruleForm.good_code = "";
      this.goods_sitem = {};
    },
    platform_idsearchChange(e) {
      const { id, code, label } = e;
      this.ruleForm.platform_id = id || "";
      this.$refs.ruleForm.validateField("platform_id");
      this.platformType = e.platform_type;
      this.ruleForm.good_code = "";
      this.goods_sitem = {};
    },
    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;
        }
      }
    },
    //省市区选择
    select_area_change(e, index) {
      this.addrForm.order_addr[index].addr_code = e;
    },
    areaChange(e, index) {
      const { code, area_code, label } = e;
      this.addrForm.order_addr[index].names = label ? [label] : [];
      this.addrForm.order_addr[index].code = area_code ? [area_code] : [];
      this.addrForm.order_addr[index].addr_code = code ? code.split(",") : [];
    },
    //省市区保存某一行
    async checkRow(rowIndex) {
      await this.$refs.addrForm.validate(async valid => {
        if (valid) {
          const { addr_code } = this.addrForm.order_addr[rowIndex];
          if (addr_code && addr_code.length === 3) {
            let arrCode = addr_code[addr_code.length - 1];
            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[rowIndex].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[rowIndex].addr_code_name = "";
          }
          this.addrForm.order_addr[rowIndex].edit = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.loading) { return; }
          this.loading = true;

          const { companyNo, customer_code, platform_id, good_num,good_price, good_code: skuCode, managerid, manager ,remark: fill_remark } = this.ruleForm;
          const model = { 
            customerCode: Array.isArray(customer_code) ? customer_code[0] : customer_code, 
            managerid: Array.isArray(managerid) ? managerid[0] : managerid,  
            fill_remark, 
            platform_id,
            good_price, 
            companyNo,
            good_num, 
            skuCode, 
            manager 
          }

          let res = await asyncRequest.create(model);
          this.loading = false;
          if (res && res.code === 0) {
            this.$notify.success({ title: "订单创建成功！", message: "" });
            this.$router.push("/sellOut/businessFiling")
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    async set_salegetprice() {
      this.priceLoding = true;
      let resModel = { isok: true, price: "0" };

      const { good_num, good_code, goodtype } = this.ruleForm;
      let key_1 = goodtype[1];
      let key_0 = goodtype[0];

      let model = { 
        skuCode: good_code, 
        sale_num: good_num,  
        is_activity: key_0 === "is_activity_0" ? "0" : "1", 
        act_code: key_0 === "is_activity_1" ? key_1 : ""
      };

      let { code, message, data } = await asyncRequest.salegetprice(model);

      if (code === 0) {
        const { sale_price } = data;
        resModel.price = sale_price + "";
        resModel.stock = data.stock;

      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
        resModel.isok = false;
      }
      this.priceLoding = false;
      return resModel;
    }
  }
};
</script>
<style lang="scss" scoped>
.salesOrderDetail {
}
</style>
