<template>
  <el-form
    :model="ruleForm"
    status-icon
    :rules="rules"
    ref="ruleForm"
    :size="'mini'"
    v-loading="loading"
    label-width="85px"
    class="demo-ruleForm"
  >
    <el-row>
      <el-col :span="24" style="padding: 12px 16px 12px 16px; text-align: right">
        <span>
          预计成本合计：<span>
            {{ newPrice }}
          </span></span
        >
        <span class="fl" style="height: 28px; font-size: 16px; line-height: 28px">{{
          title
        }}</span>
        <el-button :size="'mini'" @click="$emit('cancel')">取 消 </el-button>
        <el-button
          :size="'mini'"
          type="primary"
          v-if="type !== 'view'"
          @click="submitForm"
          >保 存
        </el-button>
      </el-col>
      <!-- <el-col :span="16">
        <el-form-item label="供应商" prop="supplierNo">
          <search-supplier
            :value="ruleForm.supplierNo"
            :placeholder="'供应商'"
            :size="'mini'"
            :names="supplierNo_name"
            :disabled="type === 'view'"
            :isDetail="type !== 'add'"
            @searchChange="supplierNosearchChange"
          />
        </el-form-item>
      </el-col> -->
      <el-col :span="18">
        <el-form-item label="商品名称" prop="pname">
          <el-input
            placeholder="商品名称"
            maxlength="100"
            :disabled="type === 'view'"
            v-model="ruleForm.pname"
          ></el-input> </el-form-item
      ></el-col>

      <el-col :span="6">
        <el-form-item label="税点" prop="tax" label-width="60px">
          <search-tax
            :value="ruleForm.tax"
            :size="'mini'"
            :disabled="type === 'view'"
            :isDetail="type !== 'add'"
            :placeholder="'税点'"
            @searchChange="taxsearchChange"
          />
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类" prop="cat_id">
              <search-sort
                :value="ruleForm.cat_id"
                :placeholder="'分类'"
                :size="'mini'"
                :names="cat_id_name"
                :disabled="false"
                :isDetail="true"
                @searchChange="cat_id_change"
              />
            </el-form-item>
            <el-form-item label="品牌" prop="brandid">
              <search-brand
                :value="ruleForm.brandid"
                :size="'mini'"
                :disabled="false"
                :isDetail="true"
                :names="brand_name"
                :placeholder="'品牌'"
                @searchChange="brandidsearchChange"
              />
            </el-form-item>
            <el-form-item label="产地" prop="origin_place">
              <select-area
                :placeholder="'产地'"
                :value="ruleForm.origin_place"
                :size="'mini'"
                :disabled="type === 'view'"
                :is-detail="id !== 'add'"
                @selectChange="selectAreaorigin_place"
              />
            </el-form-item>

            <el-form-item label="发货地" prop="delivery_place">
              <select-area
                :placeholder="'发货地'"
                :value="ruleForm.delivery_place"
                :size="'mini'"
                :disabled="type === 'view'"
                :is-detail="id !== 'add'"
                @selectChange="selectAreadelivery_place"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="padding: 0 0 0 15px">
            <el-table
              :data="spec_tableData"
              :size="'mini'"
              border
              style="width: 100%"
              max-height="175px"
            >
              <el-table-column prop="spec_name" label="规格类型" />
              <el-table-column prop="spec_value_name" label="规格值" />
              <el-table-column fixed="right" width="88px" v-if="type !== 'view'">
                <template slot="header" slot-scope="scope">
                  <span>操作</span>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="添加规格类型"
                    placement="top"
                  >
                    <i
                      class="el-icon-circle-plus-outline fr"
                      style="font-size: 18px; margin-top: 2px"
                      @click="openEdit('-1', {})"
                    />
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-tooltip effect="dark" content="修改" placement="top">
                    <i
                      class="el-icon-edit tb-icon"
                      @click="openEdit(scope.$index, scope.row)"
                    ></i>
                  </el-tooltip>
                  <el-tooltip effect="dark" content="删除" placement="top">
                    <i
                      class="el-icon-delete tb-icon"
                      @click="openDelete(scope.$index)"
                    ></i>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <!-- 弹窗 新增/修改 -->
            <base-form-add-edit
              :index="modelIndex"
              :show-model="showOtherModel"
              :sitem="modelSitem"
              @refresh="refreshEdit"
              @cancel="showOtherModel = false"
            />
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="24">
        <el-row>
          <el-col :span="24">
            <el-row>
              <el-col :span="6">
                <el-form-item label="有效期" prop="expire_day">
                  <digital-input
                    :values="ruleForm.expire_day"
                    :placeholder="'有效期'"
                    :min="1"
                    :max="100000000000"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :disabled="type === 'view'"
                    :controls="false"
                    :append="'天'"
                    @reschange="number_change($event, 'expire_day')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="物流时间" prop="delivery_day">
                  <digital-input
                    :values="ruleForm.delivery_day"
                    :placeholder="'物流时间'"
                    :min="0"
                    :max="100000000000"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :disabled="type === 'view'"
                    :controls="false"
                    :append="'天'"
                    @reschange="number_change($event, 'delivery_day')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="生产工期" prop="work_day">
                  <digital-input
                    :values="ruleForm.work_day"
                    :placeholder="'生产工期'"
                    :min="0"
                    :max="100000000000"
                    :disabled="type === 'view'"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :controls="false"
                    :append="'天'"
                    @reschange="number_change($event, 'work_day')"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="单位" prop="unit_id" label-width="60px">
                  <search-unit
                    :value="ruleForm.unit_id"
                    :size="'mini'"
                    :isDetail="true"
                    :names="unit_name"
                    :disabled="false"
                    :placeholder="'单位'"
                    @searchChange="unitsearchChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="12">
            <el-form-item label="总重量" prop="weight">
              <digital-input
                :values="ruleForm.weight"
                :placeholder="'总重量'"
                :min="0"
                :max="100000000000"
                :position="'right'"
                :precision="3"
                :disabled="type === 'view'"
                :size="'mini'"
                :controls="false"
                :append="'g'"
                @reschange="number_change($event, 'weight')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供货区域" prop="supply_area">
              <el-select
                v-model="ruleForm.supply_area"
                filterable
                :disabled="type === 'view'"
                clearable
                style="width: 100%"
                placeholder="供货区域"
              >
                <el-option
                  v-for="group in options6"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="付款方式" prop="pay_way" class="clear">
              <el-select
                v-model="ruleForm.pay_way"
                filterable
                :disabled="type === 'view'"
                clearable
                style="width: 100%"
                placeholder="付款方式"
              >
                <el-option
                  v-for="group in options10"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-col>
      <!-- <el-col :span="6">
        <el-form-item label="发货方式" prop="send_way" class="clear">
          <el-select
            v-model="ruleForm.send_way"
            filterable
            clearable
            :disabled="type === 'view'"
            style="width: 100%"
            placeholder="发货方式"
          >
            <el-option
              v-for="group in options11"
              :key="group.id"
              :label="group.name"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
      </el-col> -->
      <el-col :span="24">
        <el-row>
          <el-col :span="6">
            <el-form-item label="证书费" prop="cert_fee">
              <digital-input
                :values="ruleForm.cert_fee"
                :placeholder="'证书费'"
                :min="0"
                :disabled="type === 'view'"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :controls="false"
                :append="'元'"
                @reschange="number_change($event, 'cert_fee')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="包装费" prop="pakge_fee">
              <digital-input
                :values="ruleForm.pakge_fee"
                :placeholder="'包装费'"
                :min="0"
                :disabled="type === 'view'"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :controls="false"
                :append="'元'"
                @reschange="number_change($event, 'pakge_fee')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工艺费" prop="cost_fee">
              <digital-input
                :values="ruleForm.cost_fee"
                :placeholder="'工艺费'"
                :min="0"
                :disabled="type === 'view'"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :controls="false"
                :append="'元'"
                @reschange="number_change($event, 'cost_fee')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="加标费" prop="mark_fee">
              <digital-input
                :values="ruleForm.mark_fee"
                :placeholder="'加标费'"
                :min="0"
                :disabled="type === 'view'"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :controls="false"
                :append="'元'"
                @reschange="number_change($event, 'mark_fee')"
              />
            </el-form-item> </el-col
        ></el-row>
      </el-col>

      <el-col :span="24">
        <el-row>
          <el-col :span="6">
            <el-form-item label="打样费" prop="demo_fee">
              <digital-input
                :values="ruleForm.demo_fee"
                :placeholder="'打样费'"
                :min="0"
                :disabled="type === 'view'"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :controls="false"
                :append="'元'"
                @reschange="number_change($event, 'demo_fee')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开模费" prop="open_fee">
              <digital-input
                :values="ruleForm.open_fee"
                :placeholder="'开模费'"
                :min="0"
                :disabled="type === 'view'"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :controls="false"
                :append="'元'"
                @reschange="number_change($event, 'open_fee')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物流费" prop="delivery_fee">
              <digital-input
                :values="ruleForm.delivery_fee"
                :placeholder="'物流费'"
                :min="0"
                :disabled="type === 'view'"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :controls="false"
                :append="'元'"
                @reschange="number_change($event, 'delivery_fee')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="裸价" prop="nake_fee" class="clear">
              <digital-input
                :values="ruleForm.nake_fee"
                :placeholder="'裸价'"
                :min="0"
                :disabled="type === 'view' || is_noble"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :controls="false"
                :append="'元'"
                @reschange="number_change($event, 'nake_fee')"
              />
            </el-form-item> </el-col
        ></el-row>
      </el-col>

      <el-col :span="24" v-show="pid === '6'">
        <el-row>
          <el-col :span="12">
            <el-form-item label="金属重量" prop="noble_weight">
              <digital-input
                :values="ruleForm.noble_weight"
                :placeholder="'金属重量'"
                :min="0"
                :disabled="type === 'view'"
                :max="100000000000"
                :position="'right'"
                :precision="3"
                :size="'mini'"
                :controls="false"
                :append="'g'"
                @reschange="number_change($event, 'noble_weight')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金属种类" prop="metal_id">
              <search-metal-kind
                :value="ruleForm.metal_id"
                :size="'mini'"
                :disabled="type === 'view'"
                :isDetail="true"
                :placeholder="'金属种类'"
                @searchChange="metal_idsearchChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-col :span="6">
          <el-form-item label="启用金价" prop="is_gold_price">
            <el-select
              v-model="ruleForm.is_gold_price"
              filterable
              clearable
              :disabled="type === 'view'"
              style="width: 100%"
              placeholder="启用金价"
              @change="is_gold_price_change"
            >
              <el-option
                v-for="group in options5"
                :key="group.id"
                :label="group.name"
                :value="group.id"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <!-- 
        <el-col :span="6">
          <el-form-item label="有无工差" prop="is_diff">
            <el-select
              v-model="ruleForm.is_diff"
              filterable
              clearable
              :disabled="type === 'view'"
              style="width: 100%"
              placeholder="有无工差"
            >
              <el-option
                v-for="group in options8"
                :key="group.id"
                :label="group.name"
                :value="group.id"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-row>
            <el-col :span="12">
              <el-form-item label="配置要求" prop="config">
                <el-select
                  v-model="ruleForm.config"
                  multiple
                  :disabled="type === 'view'"
                  style="width: 100%"
                  placeholder="配置要求"
                >
                  <el-option
                    v-for="(item, index) in options9"
                    :key="item + index"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="其他配置要求" prop="other_config" label-width="120px">
                <el-input
                  placeholder="其他要求"
                  maxlength="100"
                  :disabled="type === 'view'"
                  v-model="ruleForm.other_config"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-col>

      <el-col :span="24">
        <el-form-item label="采购备注" prop="remark">
          <el-input
            placeholder="采购备注"
            maxlength="500"
            :disabled="type === 'view'"
            v-model="ruleForm.remark"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="工艺说明" prop="cost_desc">
          <el-input
            placeholder="工艺说明"
            maxlength="500"
            :disabled="type === 'view'"
            v-model="ruleForm.cost_desc"
          >
          </el-input>
        </el-form-item>
      </el-col>
      <!-- <el-col :span="24">
        <el-form-item
          label="商品图片(<1mb)"
          prop="good_img"
          class="activity-upload"
        >
          <div class="btnupload" style="position: relative">
            <img
              v-if="ruleForm.good_img"
              :src="ruleForm.good_img"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <file-upload
              class="Upload"
              :accept="'.jpg,.png,.jpeg'"
              :multiple="true"
              :disabled="type === 'view'"
              :uploadcondition="beforeAvatarUpload"
              @UploadErrorEvent="UploadErrorEventgood_img"
              @UploadSuccessEvent="UploadSuccessEventgood_img"
            ></file-upload>
          </div>
        </el-form-item>
      </el-col> -->

      <el-col :span="24">
        <el-form-item
          label="商品图片(<1mb)"
          prop="good_img"
          v-if="ruleForm.good_img"
          class="activity-upload"
        >
          <div
            class="btnupload"
            style="position: relative; margin-left: 10px"
            v-for="(item, index) in ruleForm.good_img"
            :key="index"
          >
            <img :src="ruleForm.good_img[index]" class="avatar" />
            <i
              v-if="type == 'add' || type === 'editBase' || type === 'edit'"
              class="el-icon-close"
              @click="closeImg(index, 'good_img')"
            ></i>
          </div>
          <div v-if="type == 'view' ? false : true">
            <i
              class="el-icon-plus avatar-uploader-icon"
              style="position: relative; width: 50px; height: 50px"
            >
              <file-upload
                class="Upload"
                :accept="'.jpg,.png,.jpeg'"
                :multiple="true"
                :disabled="type === 'view'"
                :uploadcondition="beforeAvatarUpload"
                @UploadErrorEvent="UploadErrorEventgood_img"
                @UploadSuccessEvent="UploadSuccessEventgood_img"
              ></file-upload>
            </i>
          </div>
        </el-form-item>
        <!-- <i class="el-icon-plus avatar-uploader-icon">
          
        </i>
            <file-upload
              class="Upload"
              :accept="'.jpg,.png,.jpeg'"
              :multiple="true"
              :disabled="false"
              :uploadcondition="beforeAvatarUpload"
              @UploadErrorEvent="UploadErrorEventgood_img"
              @UploadSuccessEvent="UploadSuccessEventgood_img"
            ></file-upload> -->
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import asyncRequest from "@/apis/workbench";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import baseFormAddEdit from "./baseFormAddEdit";
import {
  options1,
  options2,
  options3,
  options4,
  options5,
  options6,
  options7,
  options8,
  options9,
  options10,
  options11,
  rules,
} from "../columns";
export default {
  name: "goodsCostAdd",
  mixins: [resToken],
  props: ["showModel", "id", "type", "sitem", "askItem", "newTime", "editId"],
  components: {
    baseFormAddEdit,
  },
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find((item) => item.menu_route == "goodsCostAdd") ||
        {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },

  data() {
    return {
      pid: "",
      cat_id_name: "",
      // supplierNo: "",
      brand_name: "",
      unit_name: "",
      title: "",
      modelIndex: "",
      modelSitem: {},
      showOtherModel: false,
      is_noble: false,
      status: "",
      rulesThis: this.rules,
      activeName: "1",
      loading: true,

      //新实时金价
      newGoldPrice: 0,

      options1: options1,
      options2: options2,
      options3: options3,
      options4: options4,
      options5: options5,
      options6: options6,
      options7: options7,
      options8: options8,
      options9: options9,
      options10: options10,
      options11: options11,
      ruleForm: {},
      rules,
      //乘法处理
      r1: "",
      r2: "",
      //除法处理
      r3: "",
      r4: "",

      //成本合算
      newPrice: 0,
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    //图片悬浮删除
    closeImg(index, key) {
      this.ruleForm[key].splice(index, 1);
      this.$refs.ruleForm.validateField(key);
    },
    //加法精度问题
    accAdd(arg1, arg2) {
      var r1, r2, m;
      try {
        r1 = arg1.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = arg2.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }
      m = Math.pow(10, Math.max(r1, r2));
      return (arg1 * m + arg2 * m) / m;
    },

    //乘法精度问题
    accMul(arg1, arg2) {
      var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) {}
      try {
        m += s2.split(".")[1].length;
      } catch (e) {}
      let numStr =
        (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) / Math.pow(10, m);
      return numStr.toString();
    },
    //除法精度问题
    accDiv(arg1, arg2) {
      var t1 = 0,
        t2 = 0,
        c1,
        c2;
      try {
        t1 = arg1.toString().split(".")[1].length;
      } catch (e) {}
      try {
        t2 = arg2.toString().split(".")[1].length;
      } catch (e) {}
      // with (Math) {
      c1 = Number(arg1.toString().replace(".", ""));
      c2 = Number(arg2.toString().replace(".", ""));
      return (c1 / c2) * Math.pow(10, t2 - t1);
      // }
    },
    async initForm() {
      // this.supplierNo = [];
      this.loading = true;
      if (this.type === "add") {
        this.title = "新建采返商品";
      } else if (this.type === "edit") {
        this.title = "编辑采返商品";
      } else {
        this.title = "采返商品详情";
      }
      this.resetFormData();

      await this.resetForm();

      if (this.type === "edit" || this.type === "view") {
        await this.initData();
      }
      //调用实时金价获取接口
      this.golpricelast();
      //调用成本合算计算函数
      // this.computedCost()
      this.rulesThis = this.rules;
      this.setrules();
      this.loading = false;
    },
    //计算价格
    computedCost() {
      const { num } = this.askItem;
      const {
        demo_fee,
        open_fee,
        noble_weight,
        cost_fee,
        pakge_fee,
        mark_fee,
        cert_fee,
        nake_fee,
        delivery_fee,
      } = this.ruleForm;
      let a = this.accDiv(demo_fee, num); // 打样费/购买数量
      let b = this.accDiv(open_fee, num); //开模费/购买数量
      let c = this.accMul(noble_weight, this.newGoldPrice); //金属重量* 最新金价
      let d = this.accMul(cost_fee, noble_weight); //工艺费* 金属重量
      let e = this.accAdd(pakge_fee, mark_fee); //包装费+加标费
      let f = this.accAdd(cert_fee, nake_fee); //证书费+产品裸价
      if (this.is_noble) {
        this.newPrice = this.accAdd(
          this.accAdd(this.accAdd(a, b), this.accAdd(c, d)),
          this.accAdd(this.accAdd(e, f), delivery_fee)
        ).toFixed(2);
      } else {
        this.newPrice = this.accAdd(
          this.accAdd(this.accAdd(a, b), this.accAdd(e, f)),
          delivery_fee
        ).toFixed(2);
      }
      console.log(new Date().valueOf() + this.newPrice);
    },

    number_change(e, key) {
      this.ruleForm[key] = e + "" || "0";
      this.$refs.ruleForm.validateField(key);
      this.computedCost();
    },
    async initData() {
      this.loading = true;
      const res = await asyncRequest.good_detail({
        bidNo: this.editId,
      });
      const { code, data, message } = await this.useResHandle(res);
      if (code === 0) {
        const {
          bidNo,
          good_name, //string	名称
          cat_id, //array 分类
          cat_info,
          brand_id, //string	品牌id
          unit, //	string	单位
          unit_id, //单位ID
          tax, //string	税率
          // supplierNo, //	string	供应商
          cost_desc, //	string	工艺说明
          remark, //	string	采购备注
          weight, //	string	重量
          supply_area, //	string	供货区域 1 全国2 除偏远地区
          origin_place, //	string	产地
          delivery_place, // string 发货地
          delivery_day, //	string	物流天数
          expire_day, //	string	信息有效期
          good_img, //
          // good_name,
          cert_fee, //	string	证书费
          pakge_fee, //	string	打包费
          cost_fee, //	string	工艺费
          mark_fee, //	string	加标费
          demo_fee, //	string	打样费
          open_fee, //	string	开模费
          metal_id, //	string	金属类别
          noble_weight, //	string	金属重量
          is_gold_price, //	string	是否使用实时金价
          delivery_fee, //	string	物流费
          status, //		string	状态
          brand_name,
          work_day,
          pay_way,
          send_way,
          is_diff,
          config,
          nake_fee,
          other_config,
          // supplierName,
          specinfo,
        } = JSON.parse(JSON.stringify(data));
        if (specinfo && specinfo.length > 0) {
          this.spec_tableData = JSON.parse(JSON.stringify(specinfo));
        }
        this.cat_id_name = "";
        if (cat_info && cat_info.length) {
          cat_info.forEach((e, ei) => {
            if (ei === 0) {
              this.pid = e.id;
            }
            this.cat_id_name += `${ei !== 0 ? "_" : ""}${e.name}`;
          });
        }
        // this.supplierNo_name = supplierName || "";
        this.is_noble = is_gold_price === "1" && this.pid === "6";
        // this.is_noble = this.askItem.is_metal;
        this.brand_name = brand_name || "";
        this.unit_name = unit || "";
        this.ruleForm = {
          infoNo: this.id || "",
          bidNo: bidNo || "",
          infoNo: this.id || "",
          cat_id: cat_id ? [cat_id] : [],
          // supplierNo: supplierNo ? [supplierNo] : [],
          pname: good_name || "",
          expire_day: expire_day || "1", //有效期
          delivery_day: delivery_day || "0", //物流时间
          work_day: work_day || "0", //生产工期
          brandid: brand_id ? [brand_id] : [],
          unit_id: unit_id ? [unit_id] : [],
          weight: weight || "0.000",
          tax: tax ? tax + "%" : "",
          supply_area: supply_area || "",
          origin_place: origin_place ? origin_place.split(",") : [],
          delivery_place: delivery_place ? delivery_place.split(",") : [],

          cert_fee: cert_fee || "0.00",
          pakge_fee: pakge_fee || "0.00",
          cost_fee: cost_fee || "0.00",
          mark_fee: mark_fee || "0.00",
          demo_fee: demo_fee || "0.00",
          open_fee: open_fee || "0.00",
          delivery_fee: delivery_fee || "0.00",
          nake_fee: nake_fee || "0.00",
          pay_way: pay_way || "",
          send_way: send_way || "1",
          noble_weight: noble_weight || "0.000",

          metal_id: metal_id || "",
          is_gold_price: is_gold_price || "0",
          is_diff: is_diff || "0",
          config: config ? config.split(",") : [],
          other_config: other_config || "",
          remark: remark || "",
          cost_desc: cost_desc || "",
          good_img: good_img || [],
        };

        this.status = status;
        if (this.is_noble) {
          this.ruleForm.nake_fee = "0";
        }
      }
    },
    async submitForm() {
      if (this.loading) {
        return;
      }
      if (this.is_noble) {
        this.ruleForm.nake_fee = "0";
      }
      this.computedCost();
      if (this.ruleForm.good_img.length > 10) {
        this.$message.warning("上传图片不能超过10张");
        return;
      }

      // for (let key in this.ruleForm) {
      //   console.log(this.rulesThis[key]);
      //   console.log(
      //     key + "---" + this.rulesThis[key][0].required + "-----" + this.ruleForm[key]
      //   );
      // }
      await this.$refs.ruleForm.validate(async (valid) => {
        console.log(valid);
        if (valid) {
          if (!this.loading) {
            this.loading = true;
            if (this.spec_tableData.length === 0) {
              this.$message.warning("请填写规格！");
              this.loading = false;
              return;
            }
            let model = JSON.parse(JSON.stringify(this.ruleForm));
            model.cat_id = model.cat_id[model.cat_id.length - 1];
            model.brandid = model.brandid.toString();
            // model.supplierNo = model.supplierNo.toString();
            model.origin_place = model.origin_place.toString();
            model.delivery_place = model.delivery_place.toString();
            model.send_way = "1"; //发货方式 默认供应商包邮
            model.is_gold_price = "0"; //是否启用实时金价 默认否
            model.is_diff = "0"; //有无工差 默认无工差
            model.unit_id = model.unit_id.toString();
            model.config = model.config.toString();
            model.tax = parseInt(model.tax + "") + "";
            model.specinfo = [];
            let list = JSON.parse(JSON.stringify(this.spec_tableData));
            list.forEach((a) => {
              let am = {
                specid: a.specid,
                spec_value_id: a.spec_value_id,
              };
              model.specinfo.push(am);
            });
            console.log(model);
            let res = {};
            if (this.type === "add") {
              delete model["bidNo"];
              res = await asyncRequest.good_add(model);
            } else {
              res = await asyncRequest.good_update(model);
            }
            const { code, data, message } = await this.useResHandle(res);
            this.loading = false;
            if (code === 0) {
              const title = this.type === "add" ? "新建成功！" : "修改成功!";
              this.$notify.success({
                title: title,
                message: "",
              });
              this.showModelThis = false;
              // 刷新
              this.$emit("refresh");
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    async resetForm() {
      // 重置
      await this.$nextTick(async () => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.spec_tableData = [];
          // console.log(this.askItem);
          this.is_noble = false;
          const { can_id_arr, is_gold_price } = this.askItem;
          can_id_arr.forEach((e, index) => {
            if (index == 0) {
              this.pid = e;
            }
          });
          if (this.pid === "6" && is_gold_price === "1") {
            this.is_noble = true;
          }
          this.cat_id_name = this.type === "add" ? this.askItem.can_name : "";
          this.brand_name = "";
          // this.type === "add" ? this.askItem.brand : "";
          this.unit_name = "";
          let good_img = this.askItem.good_img ? this.askItem.good_img.split(",") : [];
          //this.type === "add" ? this.askItem.unit_name : "";
          this.ruleForm = {
            infoNo: this.id || "",
            cat_id: this.type === "add" ? [this.askItem.cat_id] : [],
            // supplierNo: [],
            pname: this.type === "add" ? this.askItem.good_name : "",
            expire_day: "1", //有效期
            delivery_day: "0", //物流时间
            work_day: "0", //生产工期
            brandid: [],
            // this.type === "add" && this.askItem.brand_id
            //   ? [this.askItem.brand_id]
            //   : [],
            unit_id: [],
            //this.type === "add" ? [this.askItem.unit] : [],
            weight: this.type === "add" ? this.askItem.total_weight : "0.000",
            tax: "",
            supply_area: "",
            origin_place: [],
            delivery_place: [],
            cert_fee: "0.00",
            pakge_fee: "0.00",
            cost_fee: "0.00",
            mark_fee: "0.00",
            demo_fee: "0.00",
            open_fee: "0.00",
            delivery_fee: "0.00",
            nake_fee: "0.00",
            pay_way: "",
            send_way: "1",
            noble_weight: this.type === "add" ? this.askItem.specs_weight : "0.000",
            metal_id: this.type === "add" ? this.askItem.metal_id : "",
            is_gold_price: this.type === "add" ? this.askItem.is_gold_price : "0",
            is_diff: "0",
            config:
              this.type === "add"
                ? this.askItem.config
                  ? this.askItem.config.split(",")
                  : []
                : [],
            other_config: this.type === "add" ? this.askItem.other_config : "",
            remark: "",
            cost_desc: this.type === "add" ? this.askItem.cost_desc : "",
            good_img: this.type === "add" ? good_img : [],
          };

          if (this.type === "add") {
            this.spec_tableData = JSON.parse(JSON.stringify(this.askItem.specinfo));
          }
        }
      });
    },

    openEdit(index, sitem) {
      this.modelIndex = index;
      this.modelSitem = sitem;
      this.showOtherModel = true;
    },
    openDelete(index) {
      this.spec_tableData.splice(index, 1);
    },
    //规格编辑修改结果
    refreshEdit(e) {
      let item = JSON.parse(JSON.stringify(e));
      const { index, specid, spec_name, spec_value_id, spec_value_name } = item;
      if (index + "" === "-1") {
        this.spec_tableData.push(item);
      } else {
        let findex = parseInt(index + "");
        this.spec_tableData[findex].specid = specid;
        this.spec_tableData[findex].spec_name = spec_name;
        this.spec_tableData[findex].spec_value_id = spec_value_id;
        this.spec_tableData[findex].spec_value_name = spec_value_name;
      }
      this.showOtherModel = false;
    },
    //分类选择
    async cat_id_change(e) {
      const { pid, id, label } = e;
      if (pid === "6") {
        this.$message.warning("不允许反馈贵金属商品！");
        this.pid = "";
        this.ruleForm.cat_id = [];
      } else {
        this.pid = pid || "";
        this.ruleForm.cat_id = id ? [id] : [];
      }

      this.$refs.ruleForm.validateField("cat_id");
      const { is_gold_price } = this.ruleForm;
      this.is_noble = this.pid === "6" && is_gold_price === "1";
      this.setrules();
      if (this.is_noble) {
        this.ruleForm.nake_fee = "0";
      }
      this.computedCost();
    },
    setrules() {
      let list1 = ["noble_weight", "is_gold_price", "is_diff"];
      for (let i = 0; i < list1.length; i++) {
        this.rulesThis[list1[i]][0].required = this.is_noble;
      }
      let list2 = ["metal_id", "config", "other_config"];
      for (let i = 0; i < list2.length; i++) {
        this.rulesThis[list2[i]][0].required = this.pid === "6";
      }
    },
    is_gold_price_change() {
      const { is_gold_price } = this.ruleForm;
      this.$refs.ruleForm.validateField("is_gold_price");
      this.is_noble = this.pid === "6" && is_gold_price === "1";
      this.setrules();
      if (this.is_noble) {
        this.ruleForm.nake_fee = "0";
      }
      this.computedCost();
    },
    //品牌选择
    brandidsearchChange(e) {
      const { id, code, label } = e;
      if (id) {
        this.ruleForm.brandid = [id];
      } else {
        this.ruleForm.brandid = [];
      }
      this.$refs.ruleForm.validateField("brandid");
    },
    // //供应商选择
    // supplierNosearchChange(e) {
    //   console.log(e);
    //   const { id, code, label } = e;
    //   if (id) {
    //     this.ruleForm.supplierNo = [code];
    //   } else {
    //     this.ruleForm.supplierNo = [];
    //   }
    //   this.$refs.ruleForm.validateField("supplierNo");
    // },
    //税点选择
    taxsearchChange(e) {
      this.ruleForm.tax = e;
      this.$refs.ruleForm.validateField("tax");
    },
    //单位选择
    unitsearchChange(e) {
      const { id, code, label } = e;
      if (id) {
        this.ruleForm.unit_id = [code];
      } else {
        this.ruleForm.unit_id = [];
      }
      this.$refs.ruleForm.validateField("unit_id");
    },
    //金属种类选择
    //需修改，未改完
    async metal_idsearchChange(e) {
      this.loading = true;
      const { id, code, label } = e;
      if (id) {
        this.ruleForm.metal_id = id;
      } else {
        this.ruleForm.metal_id = "";
      }
      this.$refs.ruleForm.validateField("metal_id");

      //获取实时金价
      this.golpricelast();

      this.loading = false;
    },
    //获取实时金价
    async golpricelast() {
      const { metal_id } = this.ruleForm;
      if (metal_id === "" && metal_id === "0") {
        this.newGoldPrice = 0;
        this.computedCost();
        return;
      }
      const res = await asyncRequest.golpricelast({
        type: metal_id,
      });
      const { code, data, message } = await this.useResHandle(res, true);
      if (code === 0) {
        if (data.length !== 1) {
          this.newGoldPrice = 0;
        } else {
          this.newGoldPrice = data[0].price;
        }
      } else {
        this.newGoldPrice = 0;
      }
      this.computedCost();
    },

    //仓库省市区
    selectAreaorigin_place(e) {
      this.ruleForm.origin_place = e;
      this.$refs.ruleForm.validateField("origin_place");
    },
    //发货地省市区
    selectAreadelivery_place(e) {
      this.ruleForm.delivery_place = e;
      this.$refs.ruleForm.validateField("delivery_place");
    },

    //图片上传成功
    async UploadSuccessEventgood_img(data) {
      await this.UploadSuccessEvent(1, data);
    },

    //图片上传成功
    async UploadSuccessEvent(type, data) {
      if (this.ruleForm.good_img.length > 10) {
        this.$message.warning("上传图片最多不能超过10张");
        return;
      }
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else if (url === "noSupplierNo") {
        this.$notify({
          title: "当前供应商参数错误",
          dangerouslyUseHTMLString: true,
          message: "5秒后，请您重新登录！",
        });
        await setTimeout(async () => {
          await this.logout();
        }, 5000);
      } else {
        if (type === 1) {
          this.ruleForm.good_img.push(url);
          this.$refs.ruleForm.validateField("good_img");
        } else if (type === 2) {
          this.ruleForm.good_img.push(url);
          this.$refs.ruleForm.validateField("good_img");
        }
        console.log(this.ruleForm.good_img.length);
        this.$message.success("图片上传成功!");
      }
    },
    //图片上传失败
    UploadErrorEventgood_img(res) {
      this.imgUploadError(1, res);
    },

    imgUploadError(type, res) {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
        this.$refs.ruleForm.validateField(
          type === 1 ? "good_img" : type === 2 ? "good_img" : ""
        );
      }
    },
    //判断图片规格
    beforeAvatarUpload(file) {
      let isJPG = false;
      if (
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/jpeg"
      ) {
        isJPG = true;
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        this.$message.error("图片格式不正确！");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
    resetFormData() {
      this.status = "";
      this.is_noble = false;
      this.cat_id_name = "";
      this.brand_name = "";
      this.unit_name = "";
      this.ruleForm = {
        infoNo: "",
        cat_id: [],
        // supplierNo: [],
        pname: "",
        expire_day: "1", //有效期
        delivery_day: "0", //物流时间
        work_day: "0", //生产工期
        color: "",
        model: "",
        material: "",
        brandid: [],
        unit_id: [],
        weight: "0.000",
        tax: "",
        supply_area: "",
        origin_place: [],
        delivery_place: [],
        cert_fee: "0.00",
        pakge_fee: "0.00",
        cost_fee: "0.00",
        mark_fee: "0.00",
        demo_fee: "0.00",
        open_fee: "0.00",
        delivery_fee: "0.00",
        nake_fee: "0.00",
        pay_way: "",
        send_way: "1",
        noble_weight: "0.000",
        metal_id: "",
        is_gold_price: "0",
        is_diff: "0",
        config: [],
        other_config: "",
        remark: "",
        cost_desc: "",
        good_img: [],
      };
    },
    addFormData() {
      this.status = "";
      this.is_noble = false;
      this.cat_id_name = "";
      this.brand_name = "";
      this.unit_name = "";
      this.ruleForm = {
        infoNo: "",
        cat_id: [],
        // supplierNo: [],
        pname: "",
        expire_day: "1", //有效期
        delivery_day: "0", //物流时间
        work_day: "0", //生产工期
        color: "",
        model: "",
        material: "",
        brandid: [],
        unit_id: [],
        weight: "0.000",
        tax: "",
        supply_area: "",
        origin_place: [],
        delivery_place: [],
        cert_fee: "0.00",
        pakge_fee: "0.00",
        cost_fee: "0.00",
        mark_fee: "0.00",
        demo_fee: "0.00",
        open_fee: "0.00",
        delivery_fee: "0.00",
        nake_fee: "0.00",
        pay_way: "",
        send_way: "1",
        noble_weight: "0.000",
        metal_id: "",
        is_gold_price: "0",
        is_diff: "0",
        config: [],
        other_config: "",
        remark: "",
        cost_desc: "",
        good_img: [],
      };
    },
  },
};
</script>
<style lang="scss" scoped>
.goodsCostDetail {
  .goodsCostAdd-title {
    border-top: 1px solid #ebeef5;
    span {
      height: 50px;
      line-height: 50px;
      font-family: "微软雅黑", sans-serif;
      font-weight: 400;
      font-style: normal;
      font-size: 16px;
      text-align: left;
    }
  }
}
i.el-icon-close {
  position: absolute;
  z-index: 2;
  top: 0;
  right: 0;
  color: #63cbe7;
  font-weight: bold;
  cursor: pointer;
}

// /deep/ .fileUp {
//       opacity: 10 !important;
//     width: 228px !important;
//     height: 200px !important;
//     outline: none;
//     position: static !important;
// }
</style>
