<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
            :isDetail="true"
            @searchChange="supplierNosearchChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="品牌" prop="brandid" label-width="60px">
          <search-brand
            :value="ruleForm.brandid"
            :size="'mini'"
            :disabled="false"
            :isDetail="true"
            :names="brand_name"
            :placeholder="'品牌'"
            @searchChange="brandidsearchChange"
          />
        </el-form-item>
      </el-col>

      <el-col :span="5">
        <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="5">
        <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="5">
        <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="5">
        <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="4">
        <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-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="pname">
              <el-input
                placeholder="商品名称"
                maxlength="100"
                :disabled="type === 'view'"
                v-model="ruleForm.pname"
              ></el-input>
            </el-form-item>
            <el-form-item label="产地" prop="origin_place">
                <search-area
                :value="areaInfo.origin_place.code"
                :disabled="type === 'view' || type === 'editCoin'"
                :is-detail="true"
                size="mini"
                :names="areaInfo.origin_place.label"
                placeholder="产地"
                :level="3"
                @searchChange="areaChange($event, 'origin_place')"
              />
            </el-form-item>

            <el-form-item label="发货地" prop="delivery_place">
              <search-area
                :value="areaInfo.delivery_place.code"
                :is-detail="true"
                size="mini"
                :disabled="type === 'view' || type === 'editCoin'"
                :names="areaInfo.delivery_place.label"
                placeholder="发货地"
                :level="3"
                @searchChange="areaChange($event, 'delivery_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"
                    v-if="!scope.row.isMust"
                    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="6">
        <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-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="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-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-col :span="24" v-show="pid + '' === '6'">
        <el-col :span="6">
          <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="6">
          <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-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="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-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/service/supplierPurchaseIn/supplierWorkbench";
import resToken from "@/mixins/resToken";
import companyHelper from "@/mixins/companyHelper";
import { mapGetters } from "vuex";
import baseFormAddEdit from "./baseFormAddEdit";
import { add_sum, accMul, accDiv } from "@/utils/validate";
import {
  options1,
  options2,
  options3,
  options4,
  options5,
  options6,
  options7,
  options8,
  options9,
  options10,
  options11,
  rules,
} from "../columns";
export default {
  name: "goodsCostAdd",
  mixins: [resToken,companyHelper],
  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 {
      areaInfo:{
        delivery_place:{
          code:[],
          label:[]
        },
        origin_place:{
          code:[],
          label:[]
        }
      },
      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,
      supplierNo_name:"",

      //新实时金价
      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: {
    async areaChange(e, key) {
      const { code, area_code, label } = e
      this.ruleForm[key] = code ? code.split(',') : []
      this.areaInfo[key].code = area_code ? [area_code] : []
      this.areaInfo[key].label = label ? [label] : []
      this.$refs.ruleForm.validateField(key)
    },
    //图片悬浮删除
    closeImg(index, key) {
      this.ruleForm[key].splice(index, 1);
      this.$refs.ruleForm.validateField(key);
    },
    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();
      }else{
      this.areaInfo = {
        delivery_place:{
          code:[],
          label:[]
        },
        origin_place:{
           code:[],
           label:[]
          }
        }
      }

      if(this.type === 'add'){
        this.ruleForm.supplierNo = [this.currentCompany]
        this.supplierNo_name = this.getCompanyWithCode(this.currentCompany).name
      }
      
      //调用实时金价获取接口
      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 = accDiv(demo_fee, num); // 打样费/购买数量
      let b = accDiv(open_fee, num); //开模费/购买数量
      let c = accMul(noble_weight, this.newGoldPrice); //金属重量* 最新金价
      let d = accMul(cost_fee, noble_weight); //工艺费* 金属重量
      let e = add_sum(pakge_fee, mark_fee); //包装费+加标费
      let f = add_sum(cert_fee, nake_fee); //证书费+产品裸价
      if (this.is_noble) {
        this.newPrice = add_sum(
          add_sum(add_sum(a, b), add_sum(c, d)),
          add_sum(add_sum(e, f), delivery_fee)
        ).toFixed(2);
      } else {
        this.newPrice = add_sum(
          add_sum(add_sum(a, b), add_sum(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 { code, message, data } = await asyncRequest.good_detail({
        bidNo: this.editId,
      });
      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	产地
          origin_place_cn, //	string	产地
          delivery_place, // string 发货地
          delivery_place_cn, // 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(this.type !== 'add'){
          this.areaInfo.origin_place.code =    origin_place ? [origin_place.split(',')[2]] : []
          this.areaInfo.origin_place.label =   origin_place_cn ? [origin_place_cn] : []
          this.areaInfo.delivery_place.code =  delivery_place ? [delivery_place.split(',')[2]] : []
          this.areaInfo.delivery_place.label = delivery_place_cn ? [delivery_place_cn] : []
        }

        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 || "",
          noble_weight: noble_weight || "0.000",

          metal_id: metal_id || "",
          is_gold_price: is_gold_price || "",
          is_diff: is_diff || "",
          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";
        }
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    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.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);
            }
            console.log(res);
            this.loading = false;
            if (res && res.code === 0) {
              const title = this.type === "add" ? "新建成功！" : "修改成功!";
              this.$notify.success({
                title: title,
                message: "",
              });
              this.showModelThis = false;
              // 刷新
              this.$emit("refresh");
            } else if (res && res.code >= 100 && res.code <= 104) {
              await this.logout();
            } else {
              this.$message.warning(res.message);
            }
          }
        } 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: "",
            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 : "",
            is_diff: "",
            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));
          }
          await this.set_must_spec();
        }
      });
    },

    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;
      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();
      await this.set_must_spec();
    },
    async set_must_spec() {
      const { cat_id } = this.ruleForm;
      let id = cat_id.length == 1 ? cat_id[0] : "";
      if (id) {
        const { code, message, data } = await asyncRequest.catinfo({ id: id });
        if (code === 0) {
          const { spec } = data;
          if (spec && spec.length > 0) {
            if (this.spec_tableData && this.spec_tableData.length > 0) {
              this.spec_tableData.forEach((c) => {
                c.isMust = false;
              });
              spec.forEach((a, ai) => {
                let findex = this.spec_tableData.findIndex((b) => b.specid === a.id);
                if (findex !== -1) {
                  this.spec_tableData[findex].isMust = true;
                } else {
                  this.spec_tableData.push({
                    id: "",
                    index: "1",
                    specid: a.id,
                    spec_name: a.spec_name,
                    isMust: true,
                    spec_value_name: "",
                    spec_value_id: "",
                  });
                }
              });
            } else {
              spec.forEach((a, ai) => {
                let model = {
                  id: "",
                  index: "1",
                  specid: a.id,
                  spec_name: a.spec_name,
                  isMust: true,
                  spec_value_name: "",
                  spec_value_id: "",
                };
                this.spec_tableData.push(model);
              });
            }
          }
          this.spec_tableData.map((e, ei) => {
            e.index = ei + "";
            return e;
          });

          this.spec_tableData.forEach((si, sii) => {
            this.$set(this.spec_tableData, sii, si);
          });
          console.log(this.spec_tableData);
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(message);
        }
      } else {
        this.spec_tableData.forEach((si, sii) => {
          si.isMust = false;
          this.$set(this.spec_tableData, sii, si);
        });
      }
    },
    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 { code, data } = await asyncRequest.golpricelast({
        type: metal_id,
      });
      if (code === 0) {
        if (data.length !== 1) {
          this.newGoldPrice = 0;
        } else {
          this.newGoldPrice = data[0].price;
        }
      } else if (code >= 100 && code <= 104) {
        this.newGoldPrice = 0;
        await this.logout();
      } 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 (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: "",
        noble_weight: "0.000",
        metal_id: "",
        is_gold_price: "",
        is_diff: "",
        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: "",
        noble_weight: "0.000",
        metal_id: "",
        is_gold_price: "",
        is_diff: "",
        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: #6954f0;
  font-weight: bold;
  cursor: pointer;
}

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