<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-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="companyName">
            <el-input
              placeholder="客户名称"
              maxlength="100"
              :disabled="type === 'view'"
              v-model="ruleForm.companyName"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="总数量" prop="num">
            <el-input placeholder="总数量" :disabled="type === 'view'" v-model="ruleForm.num" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="总价" class="clear">
            <el-input disabled :value="Number(total).toFixed(2)" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="业务公司" prop="customerCode">
            <search-work-company
              :value="ruleForm.customerCode"
              :names="ruleForm.customerName"
              :placeholder="'业务公司'"
              :isDetail="true"
              :size="'mini'"
              @searchChange="company_idsearchChange"
            />
          </el-form-item>
          <el-form-item label="供应商" prop="supplierNo">
            <search-supplier
              :isDetail="true"
              :value="ruleForm.supplierNo"
              :names="supplierName"
              :placeholder="'供应商'"
              :disabled="true"
              :size="'mini'"
              @searchChange="supplierNosearchChange"
            />
          </el-form-item>

          <el-form-item label="供应商订单号" prop="plat_orderCode" label-width="120px">
            <el-input placeholder="供应商订单号" v-model="ruleForm.plat_orderCode" />
          </el-form-item>


          <el-form-item label="附件" prop="fill_url">
            <div v-if="ruleForm.fill_url" class="clearfix">
              <a :href="ruleForm.fill_url" download="比价凭证">点击下载</a>

              <el-link
                :underline="false"
                @click="ruleForm.fill_url = ''"
                type="warning"
                style="margin: 0 0 0 16px"
              >删除</el-link>
            </div>

            <div class="activity-upload" v-else>
              <div class="btnupload" style="position: relative">
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <file-upload-pdf
                  class="Upload"
                  :accept="'.xlsx,.xls,.pdf,.zip,.rar,.7z'"
                  :multiple="false"
                  :uploadcondition="beforeOtherUpload"
                  @UploadErrorEvent="UploadErrorOtherproof_url"
                  @UploadSuccessEvent="UploadSuccessOtherproof_url"
                />
              </div>
              <div class="txt-tips fl">
                <p>建议大小：小于5MB</p>
                <p>文件格式：.xlsx,.xls,.pdf,.zip,.rar,.7z</p>
              </div>
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-row>
            <el-col :span="7">
              <el-form-item prop="is_determine_price" label="确定" label-width="60px">
                <el-select
                  v-model="ruleForm.is_determine_price"
                  style="width: 100%"
                  :disabled="type === 'view'"
                >
                  <el-option value="1" label="销售单价" />
                  <el-option value="0" label="采购裸价" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item
                label="采购裸价"
                prop="cgd_charge"
                v-if="ruleForm.is_determine_price === '0'"
                class="clear"
                label-width="100px"
              >
                <digital-input
                  :values="ruleForm.cgd_charge"
                  :placeholder="'采购裸价'"
                  :min="0"
                  :disabled="
                    type === 'view' || is_noble || ruleForm.is_determine_price === '1'
                  "
                  :max="100000000000"
                  :position="'right'"
                  :precision="2"
                  :size="'mini'"
                  :controls="false"
                  :append="'元'"
                  @reschange="number_change($event, 'cgd_charge')"
                />
              </el-form-item>
              <el-form-item
                label="销售单价"
                v-if="ruleForm.is_determine_price === '1'"
                prop="price"
                label-width="100px"
              >
                <digital-input
                  :values="ruleForm.price"
                  :placeholder="'销售单价'"
                  :min="0"
                  :disabled="
                    type === 'view' || is_noble || ruleForm.is_determine_price === '0'
                  "
                  :readonly="ruleForm.is_determine_price === '0'"
                  :max="100000000000"
                  :position="'right'"
                  :precision="2"
                  :size="'mini'"
                  :controls="false"
                  :append="'元'"
                  @reschange="number_change($event, 'price')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item :label="ruleForm.is_determine_price === '1' ? '采购裸价' : '销售单价'">
                <el-input
                  v-if="ruleForm.is_determine_price === '1'"
                  :disabled="true"
                  v-model="ruleForm.cgd_charge"
                  :placeholder="'采购裸价'"
                />
                <el-input v-else :disabled="true" v-model="ruleForm.price" :placeholder="'销售单价'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7">
              <el-form-item prop="type" label="确定" label-width="60px">
                <el-select v-model="ruleForm.type" style="width: 100%" :disabled="type === 'view'">
                  <el-option value="1" label="服务费金额" />
                  <el-option value="0" label="服务费比例" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item
                label="服务费比例"
                v-if="ruleForm.type === '0'"
                prop="expect_service_proportion"
                label-width="100px"
              >
                <digital-input
                  :values="ruleForm.expect_service_proportion"
                  :placeholder="'服务费比例'"
                  :min="0"
                  :disabled="type === 'view' || is_noble"
                  :max="100000000000"
                  :position="'right'"
                  :precision="2"
                  :size="'mini'"
                  :controls="false"
                  :append="'%'"
                  @reschange="number_change($event, 'expect_service_proportion')"
                />
              </el-form-item>

              <el-form-item
                label="服务费金额"
                prop="expect_service"
                label-width="100px"
                v-if="ruleForm.type === '1'"
              >
                <digital-input
                  :values="ruleForm.expect_service"
                  :placeholder="'服务费金额'"
                  :min="0"
                  :disabled="type === 'view' || is_noble"
                  :max="100000000000"
                  :position="'right'"
                  :precision="2"
                  :size="'mini'"
                  :controls="false"
                  :append="'元'"
                  @reschange="number_change($event, 'expect_service')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item :label="ruleForm.type === '1' ? '服务费比例' : '服务费金额'">
                <el-input
                  v-if="ruleForm.type === '1'"
                  :disabled="true"
                  v-model="ruleForm.expect_service_proportion"
                  :placeholder="'服务费比例'"
                />
                <el-input
                  v-else
                  :disabled="true"
                  v-model="ruleForm.expect_service"
                  :placeholder="'服务费金额'"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="产地" prop="origin_place">
                <search-area
                  :value="ruleForm.origin_place"
                  :names="origin_place_cn"
                  :is-detail="true"
                  :disabled="type === 'view'"
                  size="mini"
                  :placeholder="'产地'"
                  :level="3"
                  @searchChange="selectAreaoriginChange($event)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货地" prop="delivery_place">
                <search-area
                  :value="ruleForm.delivery_place"
                  :disabled="type === 'view'"
                  :names="delivery_place_cn"
                  :placeholder="'发货地'"
                  :is-detail="true"
                  size="mini"
                  :level="3"
                  @searchChange="selectAreadeliveryChange($event)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <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"
                    :label="group.name"
                    :value="group.id"
                    :key="group.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <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"
                    :label="group.name"
                    :value="group.id"
                    :key="group.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-col :span="24">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="good_name">
              <el-input
                :disabled="type === 'view'"
                v-model="ruleForm.good_name"
                placeholder="商品名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-row>
              <el-col :span="14">
                <el-form-item label="分类" prop="cat_id">
                  <company-sort
                    :value="ruleForm.cat_id"
                    :placeholder="'分类'"
                    :size="'mini'"
                    :names="ruleForm.cat_id_name"
                    :disabled="type === 'view' || ruleForm.customerCode.length === 0"
                    :company-no="ruleForm.customerCode"
                    :isDetail="true"
                    @searchChange="cat_id_change"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="品牌" prop="brand_id">
                  <search-brand
                    :value="ruleForm.brand_id"
                    :size="'mini'"
                    :disabled="type === 'view'"
                    :isDetail="true"
                    :names="ruleForm.brand_name"
                    :placeholder="'品牌'"
                    @searchChange="brand_idsearchChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-row>
                  <el-col :span="7">
                    <el-form-item label="单位" prop="unit_id">
                      <search-unit
                        :value="ruleForm.unit_id"
                        :size="'mini'"
                        :isDetail="true"
                        :names="ruleForm.unit_name"
                        :disabled="type === 'view'"
                        :placeholder="'单位'"
                        @searchChange="unitsearchChange"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="7">
                    <el-form-item label="税点" prop="tax">
                      <search-tax
                        :value="ruleForm.tax"
                        :size="'mini'"
                        :disabled="type === 'view'"
                        :isDetail="type !== 'add'"
                        :placeholder="'税点'"
                        @searchChange="taxsearchChange"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <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-row>
              </el-col>

              <el-col :span="7">
                <el-form-item label="有效期" prop="preservation_day">
                  <digital-input
                    :values="ruleForm.preservation_day"
                    :placeholder="'有效期'"
                    :min="1"
                    :max="100000000000"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :disabled="type === 'view'"
                    :controls="false"
                    :append="'天'"
                    @reschange="number_change($event, 'preservation_day')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <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="10">
                <el-form-item label="生产工期" prop="make_day">
                  <digital-input
                    :values="ruleForm.make_day"
                    :placeholder="'生产工期'"
                    :min="0"
                    :max="100000000000"
                    :disabled="type === 'view'"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :controls="false"
                    :append="'天'"
                    @reschange="number_change($event, 'make_day')"
                  />
                </el-form-item>
              </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-row>
          </el-col>
          <el-col :span="8" style="padding: 0 0 0 15px">
            <el-table
              :data="spec_tableData"
              :size="'mini'"
              border
              style="width: 100%"
              height="215px"
              max-height="215px"
            >
              <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" 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-row>

    <el-row v-if="is_noble">
      <el-col :span="6">
        <el-form-item label="金属重量" prop="gold_weight">
          <digital-input
            :values="ruleForm.gold_weight"
            :placeholder="'金属重量'"
            :min="0"
            :disabled="type === 'view'"
            :max="100000000000"
            :position="'right'"
            :precision="3"
            :size="'mini'"
            :controls="false"
            :append="'g'"
            @reschange="number_change($event, 'gold_weight')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="金属种类" prop="noble_metal">
          <search-metal-kind
            :value="ruleForm.noble_metal"
            :size="'mini'"
            :disabled="type === 'view'"
            :isDetail="true"
            :placeholder="'金属种类'"
            @searchChange="noble_metalsearchChange"
          />
        </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-select>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <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-row :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>
    </el-row>

    <el-form-item v-if="type !== 'view'">
      <div style="width: 100%; display: flex; justify-content: flex-end">
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>
<script>
import asyncRequest from "@/apis/service/sellOut/filing";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import baseFormAddEdit from "./baseFormAddEdit";
import { add_sum, accMul, accDiv, accSub } from "@/utils/validate";
import companyHelper from "@/mixins/companyHelper";

import {
  rules,
  options1,
  options2,
  options3,
  options4,
  options5,
  options6,
  options7,
  options8,
  options9,
  options10,
  options11,
  ruleForm1,
  other_ruleForm
} from "../config/columns";

export default {
  name: "goodsCostAdd",
  mixins: [resToken, companyHelper],
  props: ["showModel", "id", "type", "sitem", "askItem", "newTime", "editId"],
  components: {
    baseFormAddEdit
  },
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size", "business_companyNo"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          item => item.menu_route == "goodsCostAdd"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    total() {
      const { is_determine_price, expect_service, num } = this.ruleForm;
      const prop = is_determine_price === "1" ? "price" : "cgd_charge";
      return accMul(add_sum(this.ruleForm[prop], expect_service), num);
    }
  },
  watch: {
    newTime: function(val) {
      if (val) {
        this.initForm();
      }
    }
  },

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

      //新实时金价
      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: { ...ruleForm1 },
      rules,

      //成本合算
      newPrice: 0
    };
  },

  mounted() {
    this.initForm();
  },
  methods: {
    manageridChange(e) {
      const { id, label } = e;
      this.ruleForm.managerid = id ? [id] : [];
      this.ruleForm.manager = label
      this.$refs.ruleForm.validateField("managerid")
    },
    // 其他文件上传成功
    async UploadSuccessOtherproof_url(data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.fill_url = url;
        this.$message.success("文件成功!");
      }
    },

    //其他文件上传失败
    UploadErrorOtherproof_url(res) {
      if (res !== "break") {
        this.set_proof_url();
        this.$message.error("文件上传失败!");
      }
    },

    //判断其他文件规格
    beforeOtherUpload(file) {
      let isJPG = false;
      if (
        file.type === "application/vnd.ms-excel" ||
        file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
        file.type === "application/pdf" ||
        file.type === "application/x-zip-compressed"
      ) {
        isJPG = true;
      }
      let name = file.name;
      let list = name.split(".");
      if (list[list.length - 1] === "rar" || list[list.length - 1] === "7z") {
        isJPG = true;
      }

      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error("文件格式不正确！");
      }
      if (!isLt2M) {
        this.$message.error("文件大小不能超过 5MB!");
      }
      return isJPG && isLt2M;
    },
    //图片悬浮删除
    closeImg(index, key) {
      this.ruleForm[key].splice(index, 1);
      this.$refs.ruleForm.validateField(key);
    },
    async initForm() {
      this.loading = true;
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    number_change(e, key) {
      this.ruleForm[key] = e + "" || "0";
      const { is_determine_price, type } = this.ruleForm;
      if (key === "price" && String(is_determine_price) == "1") {
        this.getPrice(key);
      } else if (key === "cgd_charge" && String(is_determine_price) == "0") {
        this.getPrice(key);
      } else if (key === "expect_service" && String(type) == "1") {
        this.getPrice(key);
      } else if (key === "expect_service_proportion" && String(type) == "0") {
        this.getProp();
      } else if (key === "num") {
        this.getTotal();
      }
      if (this.$refs && this.$refs.ruleForm) {
        this.$refs.ruleForm.validateField(key);
      }
    },

    //计算单价
    getPrice(key) {
      const { is_determine_price, type } = this.ruleForm;

      if(String(type) == "1" && key === "expect_service"){
        this.ruleForm.price = Number(add_sum(this.ruleForm.cgd_charge,this.ruleForm.expect_service) || 0).toFixed(2)
        this.ruleForm.expect_service_proportion = accMul(
          this.ruleForm.cgd_charge ? accDiv(this.ruleForm.expect_service, this.ruleForm.cgd_charge) : "0",
          "100"
        ).toFixed(2);
      }else if ((key === "price" && String(is_determine_price) == "1")) {
        const Sub = accSub(
          Number(this.ruleForm.price),
          Number(this.ruleForm.expect_service)
        );
        // console.log(Sub, Number(Sub));
        this.ruleForm.cgd_charge = Number(Number(Sub) < 0 ? 0 : Sub).toFixed(2);
        const cgd_charge = Number(this.ruleForm.cgd_charge);
        this.ruleForm.expect_service_proportion = accMul(
          cgd_charge ? accDiv(this.ruleForm.expect_service, cgd_charge) : "0",
          "100"
        ).toFixed(2);
      } else if (
        (key === "cgd_charge" && String(is_determine_price) == "0") ||
        (String(type) == "0" && key === "expect_service")
      ) {
        this.ruleForm.price = add_sum(
          this.ruleForm.cgd_charge,
          this.ruleForm.expect_service
        ).toFixed(2);
        const cgd_charge = Number(this.ruleForm.cgd_charge);
        this.ruleForm.expect_service_proportion = accMul(
          cgd_charge ? accDiv(this.ruleForm.expect_service, cgd_charge) : "0",
          "100"
        ).toFixed(2);
      } else {
        console.log(3333);
      }

      this.getTotal();
    },
    //计算比例
    getProp() {
      const { is_determine_price, expect_service_proportion } = this.ruleForm;
      if (String(is_determine_price) == "0") {
        this.ruleForm.expect_service = accMul(
          accDiv(expect_service_proportion, "100"),
          this.ruleForm.cgd_charge
        ).toFixed(2);
        this.ruleForm.price = add_sum(
          this.ruleForm.expect_service,
          this.ruleForm.cgd_charge
        ).toFixed(2);
      } else if (String(is_determine_price) == "1") {
        const c1 = accMul(expect_service_proportion, this.ruleForm.price);
        const c2 = add_sum(expect_service_proportion, "100");

        this.ruleForm.expect_service = accDiv(c1, c2).toFixed(2);
        this.ruleForm.cgd_charge = Number(accSub(
          this.ruleForm.price,
          this.ruleForm.expect_service
        ) || 0).toFixed(2);
      }
      this.getTotal();
    },
    //计算总价
    getTotal() {
      //  SELECT SUBSTRING_INDEX(profile,",",-1) AS gender,COUNT(gender) FROM user_profile GROUP BY gender;
      const { num, price } = this.ruleForm;
      this.ruleForm.total = accMul(num, price).toFixed(2);
    },
    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);
          });
        } 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);
        });
      }
    },

    async submitForm() {
      try {
        await this.$refs.ruleForm.validate();

        if (!this.loading) {
          this.loading = true;
          if (this.ruleForm.good_img.length > 10) {
            this.$message.warning("上传图片不能超过10张");
            this.loading = false;
            return;
          }
          if (this.spec_tableData.length === 0) {
            this.$message.warning("请填写规格！");
            this.loading = false;
            return;
          }
          if (this.is_noble) {
            this.ruleForm.cgd_charge = "0";
          }

          const {
            is_determine_price,
            expect_service,
            expect_service_proportion
          } = this.ruleForm;
          const prop = is_determine_price === "1" ? "price" : "cgd_charge";
          const label = is_determine_price === "1" ? "销售价" : "裸价";

          if (!Number(this.ruleForm[prop]) && !this.is_noble) {
            this.$message.warning(label + "不能为空");
            this.loading = false;
            return;
          }

          if (
            !Number(expect_service) &&
            !Number(expect_service_proportion) &&
            !this.is_noble
          ) {
            this.$message.warning("服务费比例和服务费不能同时为空");
            this.loading = false;
            return;
          }

          // //没有服务费存在服务费比例 重新计算服务费
          // if (!Number(expect_service) && Number(expect_service_proportion)) {
          //   this.handleProportionrChange(expect_service_proportion);
          // }
          //
          // //没有服务费存在服务费比例或者两个都存在 以服务费计算服务费比例
          // if (
          //   (!Number(expect_service_proportion) && Number(expect_service)) ||
          //   (Number(expect_service_proportion) && Number(expect_service))
          // ) {
          //   this.handleExpectChange(expect_service);
          // }
          let model = Object.assign(
            other_ruleForm,
            JSON.parse(JSON.stringify(this.ruleForm))
          );

          model.cat_id = model.cat_id[model.cat_id.length - 1];
          model.brand_id = model.brand_id.toString();
          model.origin_place = model.originPlace;
          model.delivery_place = model.deliveryPlace;
          model.unit_id = model.unit_id.toString();
          model.config = model.config.toString();
          model.tax = parseInt(model.tax + "") + "";
          model.spec_list = [];
          model.supplierNo = model.supplierNo.toString();
          delete model.originPlace;
          let list = JSON.parse(JSON.stringify(this.spec_tableData));
          list.forEach(a => {
            let am = {
              spec_id: a.specid,
              spec_value_id: a.spec_value_id
            };
            model.spec_list.push(am);
          });

          let res = {};
          if (this.type === "add") {
            res = await asyncRequest.add({
              ...model,
            });
          } else {
            res = await asyncRequest.update({
              ...model,
            });
          }

          const { code } = 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.$router.push("/supplierSellOut/supplierFiling");
          }
        }
      } catch (err) {
        console.log(err);
      }
    },

    handleProportionrChange(e) {
      if (this.$refs && this.$refs.ruleForm) {
        this.ruleForm.expect_service_proportion = e;
        this.$refs.ruleForm.validateField("expect_service_proportion");
        const {
          price,
          cgd_charge,
          is_determine_price,
          expect_service_proportion
        } = this.ruleForm;
        const prop = is_determine_price === "1" ? "price" : "cgd_charge";
        if (!expect_service_proportion) return;
        if (Number(this.ruleForm.expect_service_proportion) > 100) {
          this.$message.warning("服务费比例不能大于100%");
          this.ruleForm.expect_service = "";
          this.ruleForm.expect_service_proportion = "";
          return;
        }
        this.ruleForm.expect_service =
          Number(this.ruleForm[prop]) === 0 || !this.ruleForm[prop]
            ? "0"
            : accMul(
                accDiv(expect_service_proportion, 100),
                this.ruleForm[prop]
              );
        this.$refs.ruleForm.validate("expect_service");
        this.$forceUpdate();
      }
    },

    handleExpectChange(e) {
      if (this.$refs && this.$refs.ruleForm) {
        this.ruleForm.expect_service = e;
        this.$refs.ruleForm.validateField("expect_service");
        const {
          price,
          cgd_charge,
          is_determine_price,
          expect_service
        } = this.ruleForm;
        if (!expect_service) return;
        const prop = is_determine_price === "1" ? "price" : "cgd_charge";
        const label = is_determine_price === "1" ? "销售价" : "裸价";
        if (Number(expect_service) > Number(this.ruleForm[prop])) {
          this.$message.warning("服务费不能大于" + label);
          this.ruleForm.expect_service = "";
          this.ruleForm.expect_service_proportion = "";
          return;
        }
        this.ruleForm.expect_service_proportion =
          Number(this.ruleForm[prop]) === 0 || !this.ruleForm[prop]
            ? "0"
            : accMul(accDiv(expect_service, this.ruleForm[prop]), 100);
        this.$refs.ruleForm.validate("expect_service_proportion");
        this.$forceUpdate();
      }
    },

    async resetForm() {
      // 重置
      await this.$nextTick(async () => {
        if (this.$refs && this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.spec_tableData = [];
          this.is_noble = false;

          if (this.type === "add") {
            this.supplierNosearchChange(
              this.getCompanyWithCode(this.currentCompany)
            );

            this.$nextTick(() => {
              this.ruleForm.preservation_day = 1;
            });
            // this.ruleForm.customerCode = this.currentCompany;
          } else if (this.type === "edit") {
            this.loading = true;
            const { code, data } = await asyncRequest.detail({
              id: this.$route.query.id
            });
            this.loading = false;
            if (code !== 0) return;

            const {
              id,
              companyName,
              num,
              is_determine_price,
              customerCode,
              customerName,
              supplierName,
              supplierNo,
              cgd_charge,
              price,
              service_charge,
              service_proportion,
              good_name,
              cat_info,
              brand_name,
              brand_id,
              unit_id,
              unit_name,
              tax,
              weight,
              preservation_day,
              delivery_day,
              make_day,
              origin_place,
              delivery_place,
              origin_place_cn,
              delivery_place_cn,
              supply_area,
              pay_way,
              remark,
              cost_desc,
              good_img,
              specinfo,
              fill_url,
              expect_service,
              noble_metal,
              config,
              gold_weight,
              other_config,
              plat_orderCode
            } = data;


            if (Number(gold_weight) !== 0) {
              this.is_noble = true;
            }

            this.ruleForm = {
              ...ruleForm1,
              plat_orderCode:plat_orderCode || "",
              other_config: other_config || "",
              gold_weight: gold_weight || "",
              noble_metal: noble_metal || "",
              config: config ? config.split(",") : [],
              expect_service: expect_service || "",
              id: id || "",
              fill_url: fill_url || "",
              is_determine_price: is_determine_price || "",
              companyName: companyName || "",
              num: num || "",
              customerCode: customerCode || "",
              customerName: customerName || "",
              supplierName: supplierName || "",
              supplierNo: supplierNo ? [supplierNo] : "",
              cgd_charge: cgd_charge || "",
              service_charge: service_charge || "",
              service_proportion: service_proportion || "",
              cat_id: cat_info ? [cat_info[cat_info.length - 1].id] : "",
              cat_id_name: cat_info
                .map(({ name }, index) => (index === 0 ? name : `_${name}`))
                .join(""),
              good_name: good_name || "",
              price: price || "",
              brand_name: brand_name ? [brand_name] : "",
              brand_id: brand_id ? [brand_id] : "",
              unit_id: unit_id ? [unit_id] : "",
              unit_name: unit_name ? [unit_name] : "",
              tax: tax ? `${tax}%` : "",
              weight: weight || "",
              preservation_day: preservation_day || "",
              delivery_day: delivery_day || "",
              make_day: make_day || "",
              originPlace: origin_place,
              deliveryPlace: delivery_place,
              origin_place: Array.isArray(origin_place)
                ? [origin_place[origin_place.length - 1]]
                : origin_place,
              delivery_place: Array.isArray(delivery_place)
                ? [delivery_place[delivery_place.length - 1]]
                : delivery_place,
              supply_area: supply_area || "",
              pay_way: pay_way || "",
              remark: remark || "",
              cost_desc: cost_desc || "",
              good_img: good_img || []
            };

            this.origin_place_cn = [origin_place_cn];
            this.delivery_place_cn = [delivery_place_cn];

            this.spec_tableData = specinfo.map(item => ({
              ...item,
              specid: item.spec_id
            }));

            console.log(this.ruleForm);
          }
        }
      });
    },

    openEdit(index, sitem) {
      this.modelIndex = index;
      this.modelSitem = sitem;
      this.showOtherModel = true;
    },
    openDelete(index) {
      this.spec_tableData.splice(index, 1);
    },
    async getAddr(_code) {
      const { data, code } = await asyncRequest.addrall({ code: _code });
      return data.province.name + "/" + data.city.name + "/" + data.area.name;
    },
    //规格编辑修改结果
    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, is_gold } = 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 = is_gold;
      this.setrules();

      if (this.is_noble) {
        this.ruleForm.cgd_charge = "0";
      }

      await this.set_must_spec();
    },
    setrules() {
      let list1 = ["gold_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 = ["noble_metal", "config", "other_config"];
      for (let i = 0; i < list2.length; i++) {
        this.rulesThis[list2[i]][0].required = this.pid === "6";
      }
    },
    //品牌选择
    brand_idsearchChange(e) {
      const { id } = e;
      this.ruleForm.brand_id = id ? [id] : [];
      this.$refs.ruleForm.validateField("brand_id");
    },
    //税点选择
    taxsearchChange(e) {
      this.ruleForm.tax = e;
      this.$refs.ruleForm.validateField("tax");
    },
    //供应商选择
    supplierNosearchChange(e) {
      console.log(e, "--");
      const { code, name } = e;
      this.ruleForm.supplierNo = code ? [code] : [];
      this.supplierName = name;
      this.$refs.ruleForm && this.$refs.ruleForm.validateField("supplierNo");
    }, //业务公司选择
    company_idsearchChange(e) {
      const { code } = e;
      this.ruleForm.customerCode = code || "";
      this.$refs.ruleForm.validateField("customerCode");
    },
    //单位选择
    unitsearchChange(e) {
      const { code } = e;
      this.ruleForm.unit_id = code ? [code] : [];
      this.$refs.ruleForm.validateField("unit_id");
    },
    //金属种类选择
    async noble_metalsearchChange(e) {
      const { id } = e;
      this.ruleForm.noble_metal = id ?? "";
      this.$refs.ruleForm.validateField("noble_metal");
    },

    async selectAreaoriginChange(e) {
      const { id, code } = e;
      this.ruleForm.origin_place = id ? [id] : [];
      this.ruleForm.originPlace = id ? code.split(",") : [];
      this.$refs.ruleForm.validateField("origin_place");
    },

    async selectAreadeliveryChange(e) {
      const { id, code } = e;
      this.ruleForm.delivery_place = id ? [id] : [];
      this.ruleForm.deliveryPlace = id ? code.split(",") : [];
      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");
        }
        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;
    }
  }
};
</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>
