<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="supplierNo">
                <search-work-company
                  :type="'1'"
                  :value="ruleForm.supplierNo"
                  :size="'mini'"
                  :placeholder="'销售方公司'"
                  :disabled="false"
                  :isDetail="false"
                  @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="6">
              <el-form-item label="所属平台" prop="platform_id">
                <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="platform_order">
                <el-input
                  v-model="ruleForm.platform_order"
                  placeholder="如：PO号"
                  maxlength="100"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="回款时间" prop="paytime">
                <el-date-picker
                  v-model="ruleForm.paytime"
                  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="workNo">
                <el-input
                  v-model="ruleForm.workNo"
                  placeholder="如：业管单号"
                  maxlength="100"
                />
              </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" v-show="ruleForm.good_code">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="活动类型" prop="goodtype">
                    <el-cascader
                      v-model="ruleForm.goodtype"
                      :options="goodtype_options"
                      placeholder="活动类型"
                      style="width: 100%"
                      :props="{ expandTrigger: 'hover' }"
                      @change="get_new_price"
                    ></el-cascader>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="凭证文件" prop="proof_id">
                    <el-tooltip
                      effect="dark"
                      content="查找历史凭证"
                      placement="top"
                      class="fr"
                    >
                      <i class="el-icon-search tb-icon" @click="showVoucherFun"></i>
                    </el-tooltip>

                    <el-tooltip
                      effect="dark"
                      v-if="ruleForm.proof_url"
                      content="删除"
                      placement="top"
                      class="fr"
                    >
                      <i class="el-icon-circle-close tb-icon" @click="proof_close"></i>
                    </el-tooltip>

                    <ul class="shangchuan-ul">
                      <li v-if="ruleForm.proof_url" class="shiping">
                        <div v-if="ruleForm.proof_type === '1'" class="clearfix">
                          <i
                            class="el-icon-video-camera hover fl"
                            style="
                              width: 28px;
                              height: 28px;
                              font-size: 20px;
                              line-height: 28px;
                              text-align: center;
                              background: rgb(0, 0, 0);
                              color: rgb(255, 255, 255);
                            "
                          />

                          <video width="250" controls class="fl">
                            <source :src="ruleForm.proof_url" type="video/mp4" />
                            <source :src="ruleForm.proof_url" type="video/avi" />
                            您的浏览器不支持Video标签。
                          </video>
                        </div>
                        <div v-else-if="ruleForm.proof_type === '2'" class="clearfix">
                          <img
                            style="width: 28px; height: 28px"
                            :src="ruleForm.proof_url"
                            class="avatar fl"
                          />
                        </div>
                        <div v-else class="clearfix">
                          <a :href="ruleForm.proof_url" download="凭证文件">点击下载</a>
                        </div>
                      </li>
                      <li v-else class="shiping">暂无凭证</li>
                    </ul>
                  </el-form-item>
                </el-col>
                <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-col :span="12">
                  <el-form-item label="销售数量" prop="good_num">
                    <digital-input
                      :values="ruleForm.good_num"
                      :name="'ruleForm.good_num'"
                      :placeholder="'销售数量'"
                      :min="0"
                      :disabled="false"
                      :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="12">
                  <el-form-item label="销售单价" prop="new_good_price">
                    <digital-input
                      :values="ruleForm.new_good_price"
                      :placeholder="'销售数量'"
                      :min="ruleForm.good_price || 0"
                      :disabled="ruleForm.good_price === '0'"
                      :max="
                        ruleForm &&
                        ruleForm.goodtype &&
                        ruleForm.goodtype.length === 2 &&
                        (ruleForm.goodtype[1] == '2' || ruleForm.goodtype[1] == '3')
                          ? 0
                          : 100000000000
                      "
                      :position="'right'"
                      :precision="2"
                      :size="'mini'"
                      :controls="false"
                      :append="''"
                      @reschange="number_change($event, 'new_good_price')"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </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"
                :active="true"
                :show-model="showModel"
                @resultList="resultList"
                @cancel="showModel = false"
              />
            </el-col>
          </el-row>
        </el-form>
      </el-col>

      <el-col
        :span="24"
        style="padding: 0 0 22px 0"
        v-if="ruleForm.sendtype && ruleForm.sendtype === '1'"
      >
        <el-form :model="addrForm" ref="addrForm" :size="'mini'">
          <el-table
            :data="addrForm.order_addr"
            border
            :size="'mini'"
            style="width: 100%"
            max-height="200px"
            row-key="key"
          >
            <el-table-column type="index" width="50" 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"
                    placeholder="收货总数"
                    maxlength="20"
                    :disabled="!scope.row.edit"
                  />
                </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"
                    placeholder="收件联系人"
                    maxlength="10"
                    :disabled="!scope.row.edit"
                  />
                </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"
                    placeholder="收货联系电话"
                    maxlength="11"
                    :disabled="!scope.row.edit"
                  />
                </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"
                    placeholder="收货省市区"
                    :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"
                    placeholder="详细地址"
                    maxlength="100"
                    :disabled="!scope.row.edit"
                  />
                </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"
        />

        <show-voucher-model
          :showModel="showVoucher"
          :id="goods_sitem.spuCode"
          @cancel="showVoucher = false"
          @searchChange="resvoucher"
        />
      </el-col>
      <el-col
        :span="24"
        style="
          text-align: right;
          padding: 0 0 20px 0;
          display: flex;
          justify-content: space-between;
        "
      >
        <p>
          订单总金额：
          {{
            priceAccMul(
              ruleForm && ruleForm.good_num ? ruleForm.good_num : "0",
              ruleForm && ruleForm.new_good_price
                ? ruleForm && ruleForm.new_good_price
                : "0"
            )
          }}
        </p>
        <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/salesOrder";
import {
  isnumber,
  isMobile,
  isChinese,
  isEmoticon,
  isSpecialSymbol,
  hasSpace,
  isAddr,
} from "@/utils/validate";
import inAddrModel from "@/components/in-addr-model";
import showVoucherModel from "@/components/show-voucher-model";
import searchGoodOnlineModal from "@/components/search-good-online-modal";
import { addColumns } from "./ShowDataTableColumns";
import { mapGetters } from "vuex";
import { accMul } from "@/utils/validate";
export default {
  name: "salesOrderDetail",
  mixins: [mixinPage, resToken],
  props: ["newTime", "id", "sitem", "type"],
  computed: {
    ...mapGetters(["business_companyNo"]),
  },
  components: {
    inAddrModel,
    showVoucherModel,
    searchGoodOnlineModal,
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  computed: {
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "salesOrderDetail"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },

  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 {
      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;
        },
      },
      goodtype_options: [
        {
          value: "is_activity_0",
          label: "不参与活动",
          children: [
            {
              value: "1",
              label: "常规商品",
            },
            {
              value: "2",
              label: "赠品",
            },
            {
              value: "3",
              label: "样品",
            },
          ],
        },
        {
          value: "is_activity_1",
          label: "参与活动",
          children: [],
        },
      ],
      sendtype_options: [
        {
          value: "1",
          label: "直接发货",
        },
        {
          value: "2",
          label: "延时发货",
        },
      ],
      ruleForm: {
        order_type: "1",
        supplierNo: "", //销售方编码
        customer_code: [], // 企业客户选择
        platform_id: "",
        arrtime: "", //要求到货时间
        new_good_price: "0",
        proof_id: "", //凭证ID
        proof_type: "", //凭证类型
        proof_url: "", //凭证地址
        activity_stock: "0",
        is_activity: "0", //是否参与活动,
        goodtype: ["is_activity_0", "1"], //活动类型
        good_num: "0", //商品数量
        good_price: 0, //商品单价
        platform_order: "", //平台订单号
        paytime: "", //承诺回款时间
        workNo: "", //其他单号
        sendtype: "1", //发货方式
        remark: "", //备注
        good_code: "", // 商品编号
      },
      rulesThis: this.rules,
      rules: {
        supplierNo: [
          {
            required: true,
            message: "请选择销售方公司",
            trigger: "change",
          },
        ],
        customer_code: [
          {
            type: "array",
            required: true,
            message: "请选择企业客户",
            trigger: "change",
          },
        ],
        platform_id: [
          {
            required: true,
            message: "请选择所属平台",
            trigger: "change",
          },
        ],
        arrtime: [
          {
            required: true,
            message: "要求到货时间",
            trigger: "change",
          },
        ],
        new_good_price: [
          {
            required: true,
            message: "销售单价不能为空！",
            trigger: "blur",
          },
        ],
        proof_id: [
          {
            required: false,
            message: "请选择凭证文件",
            trigger: "change",
          },
        ],

        goodtype: [
          {
            type: "array",
            required: true,
            message: "请选择活动类型",
            trigger: "change",
          },
        ],
        good_num: [
          {
            required: true,
            message: "请选择活动类型",
            trigger: "change",
          },
        ],
        sendtype: [
          {
            required: true,
            message: "请选择发货方式",
            trigger: "change",
          },
        ],
        good_code: [
          {
            required: true,
            message: "请选择销售商品",
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: true,
            message: "备注不能为空",
            trigger: "blur",
          },
        ],
      },
      addrForm: {
        order_addr: [], //收货地址
      },
      delAddrList: [],
      delStockList: [],
      addrRules: {
        receipt_quantity: {
          required: true,
          validator: validateWeight,
          trigger: "blur",
        },

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

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

      loading: false,
      queryId: "",
      status: "",
      goods_sitem: {},
      order_good_num: {
        ogood_type: "",
        ogood_num: "0",
      },
      priceLoding: false,
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    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 = {
            order_type: "1",
            supplierNo: this.business_companyNo || "", //销售方编码
            customer_code: [], // 企业客户选择
            platform_id: "",
            arrtime: "", //要求到货时间
            new_good_price: "",
            proof_id: "", //凭证ID
            proof_type: "", //凭证类型
            proof_url: "", //凭证地址
            activity_stock: "0",
            goodtype: ["is_activity_0", "1"], //活动类型
            good_num: "0", //商品数量
            good_price: 0, //系统商品单价
            platform_order: "", //平台订单号
            paytime: "", //承诺回款时间
            workNo: "", //其他单号
            sendtype: "1", //发货方式
            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 && provice_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);
            });
          }
        }
      });
    },
    resvoucher(e) {
      const { id, proof_type, proof_url } = e;
      this.ruleForm.proof_id = id || "";
      this.ruleForm.proof_type = proof_type || "";
      this.ruleForm.proof_url = proof_url || "";
      this.$refs.ruleForm.validateField("proof_id");
      this.showVoucher = false;
    },
    proof_close() {
      this.ruleForm.proof_id = "";
      this.ruleForm.proof_type = "";
      this.ruleForm.proof_url = "";
      this.$refs.ruleForm.validateField("proof_id");
    },
    addrRefresh(e) {
      const { list } = e;
      this.addrForm.order_addr.push(...list);
    },
    async resultList(e) {
      this.showModel = false;
      if (e.length === 1) {
        let ssitem = JSON.parse(JSON.stringify(e[0]));
        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");
      this.ruleForm.proof_id = "";
      this.ruleForm.proof_url = "";
      this.ruleForm.proof_type = "";
      this.$refs.ruleForm.validateField("proof_id");
      if (e.length === 1) {
        await this.get_goods_active();
      }
    },
    async get_goods_active() {
      const { good_code, supplierNo, platform_id } = this.ruleForm;
      let model = {
        skuCode: good_code,
        companyNo: supplierNo,
        platform_id,
      };
      const { code, data, message } = await asyncRequest.goods_active(model);
      if (code === 0) {
        const { act, good } = data;
        let actlist = act.length > 0 ? JSON.parse(JSON.stringify(act)) : [];
        actlist.forEach((a) => {
          a.value = a.activity_code;
          a.label = a.activity_name;
        });
        this.goodtype_options[1].children = [];
        this.goodtype_options[1].children.push(...actlist);
        let goodItem = good.length > 0 ? JSON.parse(JSON.stringify(good[0])) : {};
        if (goodItem.good_name) {
          this.goodtype_options[0].children.map((b) => {
            b.activity_stock = goodItem ? goodItem.stock_num + "" : "0";
            return b;
          });
          console.log(this.goodtype_options);
        }
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    async get_goods_detail(skuCode) {
      let { code, data, message } = await asyncRequest.goods_detail({
        skuCode: skuCode,
      });
      if (code === 0) {
        this.goods_sitem = data;
        // console.log("1111111111111111", this.goods_sitem);
        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";
      if (key === "new_good_price") {
        console.log(key + "----" + this.ruleForm.new_good_price);
      }

      this.$refs.ruleForm.validateField(key);
      if (key === "good_num") {
        await this.get_new_price();
      }
    },
    async get_new_price() {
      console.log(
        this.ruleForm.goodtype,
        this.ruleForm.goodtype.length === 2,
        this.ruleForm.goodtype[1] == "2" || this.ruleForm.goodtype[1] == "3"
      );

      const { goodtype, good_num } = this.ruleForm;

      let oldGood_type = goodtype.length === 2 ? goodtype[1] : "";

      if (oldGood_type == 2 || oldGood_type == 3) {
        this.ruleForm.good_price = 0;
      }

      const { ogood_type, ogood_num } = this.order_good_num;
      console.log(
        `oldGood_type${oldGood_type}-ogood_type${ogood_type}-good_num${good_num}-ogood_num${ogood_num}`
      );
      if (oldGood_type === ogood_type && good_num === ogood_num) {
        this.order_good_num = {
          ogood_type: goodtype.length === 2 ? goodtype[1] : "",
          ogood_num: this.ruleForm.good_num,
        };
        return;
      }

      //activity_stock
      if (goodtype.length === 2) {
        this.goodtype_options.forEach((a) => {
          if (a.children && a.children.length) {
            a.children.forEach((b) => {
              if (b.value === goodtype[1]) {
                console.log(b.activity_stock);
                this.ruleForm.activity_stock = b.activity_stock || "0";
              }
            });
          }
        });
      } else {
        this.ruleForm.activity_stock = 0 + "";
      }
      if (!this.priceLoding) {
        const { isok, price, stock } = await this.set_salegetprice();
        this.ruleForm.good_price = isok ? price : 0;
      }

      this.order_good_num = {
        ogood_type: goodtype.length === 2 ? goodtype[1] : "",
        ogood_num: this.ruleForm.good_num,
      };
    },
    change_good_code() {
      const { supplierNo, platform_id } = this.ruleForm;
      if (supplierNo === "") {
        this.$message.warning("请选择销售方公司！");
        return;
      }
      if (platform_id === "") {
        this.$message.warning("请选择所属平台！");
        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.supplierNo = 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.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;
    },
    //省市区保存某一行
    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];
            // 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[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;
        }
      });
    },
    // 删除收货地址操作
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          const { sendtype, good_num, goodtype } = JSON.parse(
            JSON.stringify(this.ruleForm)
          );
          const { order_addr } = JSON.parse(JSON.stringify(this.addrForm));

          let key_0 = goodtype[0];
          let key_1 = goodtype[1];
          if (order_addr.length === 0 && sendtype === "1") {
            this.$message.warning("至少填写一条地址信息！");
            this.loading = false;
            return;
          }
          let model = JSON.parse(JSON.stringify(this.ruleForm));
          model.addrlist = [];
          model.customer_code = model.customer_code.toString();
          const { good_price, new_good_price } = model;
          let a = accMul(good_price, "1"),
            b = accMul(new_good_price, "1");
          if (a !== b) {
            model.good_price = model.new_good_price;
          }
          // if (model.new_good_price == model.good_price) {
          // model.good_price = model.new_good_price;
          // }
          delete model["proof_type"];
          delete model["proof_url"];
          delete model["new_good_price"];
          if (sendtype === "1") {
            let addrT = 0,
              isAEdit = false;

            order_addr.forEach((v2) => {
              if (v2.edit) {
                isAEdit = true;
              }
              addrT += parseInt(v2.receipt_quantity);
              let model2 = {
                contactor: v2.contactor,
                mobile: v2.mobile,
                addr: v2.addr,
                receipt_quantity: v2.receipt_quantity,
                addr_code: v2.addr_code,
              };
              model.addrlist.push(model2);
            });

            if (isAEdit) {
              this.$message.warning("请保存地址信息！");
              this.loading = false;
              return;
            }
            if (good_num * 1 !== addrT) {
              this.$message.warning("地址收货总数与销售总数量不一致！");
              this.loading = false;
              return;
            }
          }
          let priceres = await this.set_salegetprice();
          if (!priceres.isok) {
            this.loading = false;
            return;
          }
          model.is_activity = key_0 === "is_activity_0" ? "0" : "1";
          model.goodtype = key_0 === "is_activity_1" ? "1" : key_1;
          model.act_code = key_0 === "is_activity_1" ? key_1 : "";
          let res = await asyncRequest.add(model);
          this.loading = false;
          if (res && res.code === 0) {
            this.$notify.success({
              title: "订单创建成功！",
              message: "",
            });

            this.$emit("refresh");
          } 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 : "",
      };
      console.log(model);
      let { code, message, data } = await asyncRequest.salegetprice(model);
      console.log(code, message, data);
      if (code === 0) {
        const { sale_price } = data;
        resModel.price = sale_price + "";

        let oldGood_type = goodtype.length === 2 ? goodtype[1] : "";

        if (key_0 === "is_activity_0" && (oldGood_type == 2 || oldGood_type == 3)) {
          resModel.price = 0 + "";
        }
      } 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>
