<template>
  <el-form
    ref="ruleForm"
    :loading="loading"
    :model="ruleForm"
    status-icon
    :size="'mini'"
    :rules="rulesThis"
    label-width="86px"
    style="width: 100%"
    class="demo-ruleForm"
  >
    <el-row>
      <el-col :span="6">
        <el-form-item label="竞价类型" prop="is_project">
          <el-select
            v-model="ruleForm.is_project"
            style="width: 100%"
            placeholder="竞价类型"
            clearable
            :disabled="type === 'view' || type === 'edit' || type === 'copy-edit'"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
<!--      <el-col :span="6">-->
<!--        <el-form-item label="支付渠道" prop="pay_id">-->
<!--          <search-pay-->
<!--            :value="ruleForm.pay_id"-->
<!--            :disabled="type === 'view' || ruleForm.is_project === '1'"-->
<!--            :size="'mini'"-->
<!--            :is_show="'1'"-->
<!--            :isDetail="type === 'view' || ruleForm.is_project === '1'"-->
<!--            :names="pay_name"-->
<!--            :placeholder="'支付渠道'"-->
<!--            @searchChange="pay_id_change"-->
<!--          />-->
<!--        </el-form-item>-->
<!--      </el-col>-->
      <el-col :span="6">
        <el-form-item label="竞价截止时间" label-width="110px" prop="endtime">
          <el-date-picker
            v-model="ruleForm.endtime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
            :disabled="type === 'view'"
            :picker-options="pickerOptions"
            placeholder="竞价截止时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="所属平台" prop="platform_code">
          <search-terrace
            :value="ruleForm.platform_code"
            :disabled="type === 'view' || type === 'edit'"
            :size="'mini'"
            :is_show="'1'"
            :isDetail="type === 'view' || type === 'edit'"
            :names="platform_name"
            :placeholder="'所属平台'"
            @searchChange="platform_code_codesearchChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="销售方" prop="companyNo">
       <search-work-company
         :value="ruleForm.companyNo"
         :placeholder="'销售方公司'"
         :disabled="type === 'view' || type === 'edit' || type === 'copy-edit'"
         :size="'mini'"
         :isDetail="type === 'view' || type === 'edit' || type === 'copy-edit'"
         @searchChange="company_idsearchChange" 
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="购买方" prop="khNo">
          <search-customer
            :value="ruleForm.khNo"
            :names="ruleForm.khname"
            :placeholder="'购买方公司'"
            :size="'mini'"
            @searchChange="customerChange"
            :disabled="type === 'view' || type === 'edit'"
            :is-detail="type === 'view' || type === 'edit' || type === 'copy-edit'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="收货区域" prop="area">
            <search-area
              :value="areaCode"
              :is-detail="type === 'view' || type === 'edit' || type === 'copy-edit'"
              :disabled="type === 'view' || type === 'edit'"
              :size="'mini'"
              :detail-select="true"
              :level="2"
              :names="areaLabel"
              :placeholder="'收货区域'"
              @searchChange="areasearchChange"
            />
        </el-form-item>
      </el-col>

      <el-col :span="24" v-show="ruleForm.is_project === '1'">
        <el-form-item label="项目信息" prop="projectNo" class="clear">
          <show-data-table
            :newTime="fnewTime"
            v-if="
              fnewTime !== '' &&
              projectSitem &&
              projectSitem.projectNo &&
              ruleForm.projectNo !== ''
            "
            :sitem="projectSitem"
            border
            :columns="projectColumns"
          />
          <div class="hasHover" v-else @click="showProjectModel = true">
            <el-alert
              center
              show-icon
              title="点击此处选择项目"
              type="warning"
              :closable="false"
            />
          </div>
        </el-form-item>
        <el-form-item label="项目商品要求" required>
          <el-table
            :data="ptableData"
            :size="'mini'"
            border
            stripe
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column prop="good_type" label="商品类型" width="80px">
              <template slot-scope="scope">
                <el-tag
                  :size="'mini'"
                  v-text="
                    (
                      statusOptions.find((item) => item.value == scope.row.good_type) ||
                      {}
                    ).label || '--'
                  "
                ></el-tag
              ></template>
            </el-table-column>
            <el-table-column prop="budget_price" label="预算单价" width="110" />
            <el-table-column prop="num" label="购买数量" width="110" />
            <el-table-column prop="cat_name" label="商品分类" />
            <el-table-column prop="good_img" label="图片" width="70">
              <template slot-scope="scope">
                <div
                  v-if="scope.row.good_img"
                  style="width: 20px; height: 20px"
                  class="hover"
                  v-viewer
                >
                  <img
                    :src="scope.row.good_img"
                    style="display: inline-block; width: 100%; height: 100%"
                    alt=""
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="good_name" label="商品名称" />
          </el-table>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-row>
          <el-col :span="8">
            <el-form-item label="到货日期" prop="arrival_time">
              <el-date-picker
                v-model="ruleForm.arrival_time"
                type="date"
                style="width: 100%"
                :disabled="
                  type === 'view' || (type === 'edit' && ruleForm.is_project === '1')
                "
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions1"
                placeholder="到货日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否多地" prop="is_addrs">
              <el-select
                v-model="ruleForm.is_addrs"
                placeholder="是否多地"
                :disabled="type === 'view'"
                style="width: 100%"
              >
                <el-option
                  v-for="item in is_addrs_options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6" style="margin-bottom:1px">
            <el-form-item label="预算单价" prop="budget_price">
              <digital-input
                :values="ruleForm.budget_price"
                :placeholder="'预算单价'"
                :min="0"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :size="'mini'"
                :disabled="
                  type === 'view' || (type === 'edit' && ruleForm.is_project === '1')
                "
                :controls="false"
                :append="'元'"
                @reschange="digitalInput($event, 'budget_price')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4" style="margin-bottom:1px">
            <el-form-item label="数量" prop="num" label-width="60px">
              <digital-input
                :values="ruleForm.num"
                :placeholder="'数量'"
                :min="0"
                :max="100000000000"
                :position="'right'"
                :precision="0"
                :size="'mini'"
                :disabled="
                  type === 'view' || (type === 'edit' && ruleForm.is_project === '1')
                "
                :controls="false"
                :append="''"
                @reschange="digitalInput($event, 'num')"
              />
            </el-form-item>
          </el-col>

            <el-col :span="8">
            <el-form-item label="品牌" prop="brand_id">
              <search-brand
                :value="ruleForm.brand_id"
                :size="'mini'"
                :isDetail="type === 'view' || type === 'edit' || type === 'copy-edit'"
                :names="brand_name"
                :disabled="type === 'view' || type === 'edit'"
                :placeholder="'品牌'"
                @searchChange="brand_id_searchChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否定制" prop="is_custom">
              <el-select
                v-model="ruleForm.is_custom"
                placeholder="是否定制"
                :disabled="type === 'view'"
                style="width: 100%"
              >
                <el-option
                  v-for="item in is_custom_options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="重量" prop="total_weight">
              <digital-input
                :values="ruleForm.total_weight"
                :placeholder="'重量'"
                :min="0"
                :max="100000000000"
                :position="'right'"
                :precision="3"
                :controls="false"
                :size="'mini'"
                :append="'g'"
                :disabled="type === 'view'"
                @reschange="digitalInput($event, 'total_weight')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="单位" prop="unit" label-width="60px">
              <search-unit
                :value="ruleForm.unit"
                :disabled="type === 'view'"
                :size="'mini'"
                :isDetail="type === 'view' || type === 'edit' || type === 'copy-edit'"
                :names="unit_name"
                :placeholder="'商品单位'"
                @searchChange="unitsearchChange"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商品分类" prop="cat_id">
              <search-sort
                :value="ruleForm.cat_id"
                :placeholder="'商品分类'"
                :disabled="type === 'view' || type === 'edit'"
                :size="'mini'"
                :names="cat_id_name"
                :isDetail="type === 'view' || type === 'edit' || type === 'copy-edit'"
                @searchChange="goods_class_change"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="good_name">
              <el-input
                v-model="ruleForm.good_name"
                :disabled="type === 'view'"
                placeholder="商品名称"
                maxlength="100"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工艺说明" prop="cost_desc">
              <el-input
                v-model="ruleForm.cost_desc"
                :disabled="type === 'view'"
                placeholder="工艺说明"
                maxlength="500"
              />
            </el-form-item>
            <el-form-item label="产品用途" prop="use_desc">
              <el-input
                v-model="ruleForm.use_desc"
                :disabled="type === 'view'"
                placeholder="产品用途"
                maxlength="500"
              />
            </el-form-item>
            <el-form-item label="商品备注" prop="remark">
              <el-input
                v-model="ruleForm.remark"
                :disabled="type === 'view'"
                placeholder="商品备注"
                maxlength="500"
              />
            </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%"
              height="120px"
            >
              <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-col :span="24">
            <el-row>
              <el-col :span="12" v-show="is_noble">
                <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 config_options"
                      :key="item + index"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-show="is_noble">
                <el-form-item label="金属克重" prop="specs_weight">
                  <digital-input
                    :values="ruleForm.specs_weight"
                    :placeholder="'金属克重'"
                    :min="0"
                    :max="100000000000"
                    :position="'right'"
                    :precision="3"
                    :controls="false"
                    :size="'mini'"
                    :disabled="type === 'view'"
                    :append="'g'"
                    @reschange="digitalInput($event, 'specs_weight')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-show="is_noble">
                <el-form-item label="启用金价" prop="is_gold_price">
                  <el-select
                    v-model="ruleForm.is_gold_price"
                    placeholder="启用金价"
                    :disabled="type === 'view'"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in is_gold_price_options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" style="text-align: right">
                <el-row>
                  <el-col :span="8">
                    <el-form-item
                      label="商品图片"
                      prop="good_img"
                      :disabled="id == '007'"
                    >
                      <div class="activity-upload clear">
                        <div class="btnupload">
                          <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"
                            :disabled="
                              type === 'view' || (type !== 'view' && ruleForm.p_good_img)
                            "
                            :accept="'.jpg,.png,.jpeg'"
                            :multiple="true"
                            :uploadcondition="beforeAvatarUpload"
                            @UploadErrorEvent="UploadErrorEvent"
                            @UploadSuccessEvent="UploadSuccessEvent"
                          ></file-upload>
                        </div>

                        <div class="txt-tips fl">
                          <p>小于1Mb</p>
                        </div>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" class="clear">
                    <el-form-item
                      label="附件"
                      prop="enclosure_file"
                      class="activity-upload"
                    >
                      <div v-if="ruleForm && ruleForm.enclosure_file" class="clearfix tl">
                        <a :href="ruleForm.enclosure_file" download="附件" class="fl"
                          >点击下载</a
                        >

                        <el-link
                          :underline="false"
                          v-if="type !== 'view'"
                          @click="deleteUrl()"
                          type="warning"
                          style="margin: 0 0 0 16px"
                          class="fr"
                          >删除</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="'.zip,.rar,.7z,.doc,.docx,.xlsx,.xls,.pdf'"
                            :multiple="false"
                            :uploadcondition="beforeOtherUpload"
                            @UploadErrorEvent="UploadErrorOtherenclosure_file"
                            @UploadSuccessEvent="UploadSuccessOtherenclosure_file"
                          />
                        </div>
                        <div class="txt-tips fl">
                          <p>建议大小：小于5MB</p>
                          <p>文件格式：.zip,.rar,.7z</p>
                          <p>.doc,.docx,.xlsx,.xls,.pdf</p>
                        </div>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" v-show="is_noble">
                    <el-form-item label="金属种类" prop="metal_id">
                      <search-metal-kind
                        :value="ruleForm.metal_id"
                        :size="'mini'"
                        :disabled="type === 'view'"
                        :isDetail="type !== 'add'"
                        :placeholder="'贵金属种类'"
                        @searchChange="noble_metalsearchChange"
                      />
                    </el-form-item>
                    <el-form-item
                      v-if="ruleForm.is_gold_price === '1'"
                      label="当前金价"
                      style="margin: 0 0 0 0"
                    >
                      <el-input
                        v-model="ruleForm.gold_price"
                        disabled
                        placeholder="当前金价"
                        maxlength="500"
                      >
                        <template slot="append">元</template></el-input
                      >
                    </el-form-item>
                  </el-col>
                  <el-col :span="16" v-show="is_noble">
                    <el-form-item
                      label="其他配置要求"
                      prop="other_config"
                      label-width="120px"
                    >
                      <el-input
                        v-model="ruleForm.other_config"
                        :disabled="type === 'view'"
                        type="textarea"
                        :rows="2"
                        placeholder="其他配置要求"
                        maxlength="250"
                        show-word-limit
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" class="fr tr">
                    <div class="lsac">
                      竞价单总额：
                      {{
                        priceAccMul(
                          ruleForm && ruleForm.budget_price ? ruleForm.budget_price : "0",
                          ruleForm && ruleForm.num ? ruleForm.num : "0"
                        )
                      }}
                      (元)
                    </div>
                    <el-button
                      v-if="type !== 'view'"
                      type="primary"
                      :size="'mini'"
                      @click="submitForm"
                      >保 存
                    </el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import asyncRequest from "@/apis/service/sellOut/zixunOrder";
import resToken from "@/mixins/resToken";
import { edutRules } from "../columns";
import baseFormAddEdit from "./baseFormAddEdit";
import { mapGetters } from "vuex";
import { accMul } from "@/utils/validate";
import { projectColumns } from "./ShowDataTableColumns";
import companyHelper from '@/mixins/companyHelper'
export default {
  name: "handover",
  props: ["id", "sitem", "newTime", "type"],
  mixins: [resToken, companyHelper],
  computed: {
    ...mapGetters(["business_companyNo"]),
  },
  components: {
    baseFormAddEdit,
  },
  data() {
    return {
      areaCode:[],
      areaLabel:[],
      od_form: null,
      projectColumns,
      companyName:'',
      projectSitem: null,
      fnewTime: "",
      unit_name: "",
      modelIndex: "",
      modelSitem: {},
      brand_name: "",
      showOtherModel: false,
      platform_name: "",
      cat_id_name: "",
      is_noble: false,
      multipleSelection: [],
      pay_name: "",
      is_addrs_options: [
        { value: "0", label: "一地" },
        { value: "1", label: "多地" },
      ],
      is_custom_options: [
        { value: "0", label: "非定制" },
        { value: "1", label: "定制" },
      ],
      is_gold_price_options: [
        { value: "0", label: "不启用" },
        { value: "1", label: "启用" },
      ],
      config_options: ["证书", "包装盒", "绒布袋", "标签", "其他"],
      ptableData: [],
      showModel: false,
      editItem: {},
      spec_tableData: [],
      options: [
        { value: "0", label: "非项目" },
        { value: "1", label: "项目" },
      ],
      statusOptions: [
        { value: "1", label: "竞品" },
        { value: "2", label: "竞聘" },
      ],
      configOptions: ["证书", "包装盒", "绒布袋", "标签", "其他"],
      poptions: [],
      loading: false,
      selectLoading: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 60 * 60 * 24 * 1000;
        },
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() <= Date.now();
        },
      },
      status: "", //存储详情接口返的状态
      ruleForm: {
        is_project: "0", //竞价类型 1非项目2项目，
        projectNo: "", //项目编号
        khNo: [], //客户编号
        khname: "", //客户名称
        companyNo: "",
        endtime: "", //竞价截止时间
        pendtime: "", //项目竞价截止时间
        platform_code: "", //平台id
        pay_id: "0",
        puse_desc: "",
        budget_total: "",
        arrtime: "",
        p_cat_info: [],
        p_cat_id: "",
        p_budget_price: "",
        p_pgNo: "",
        p_num: "",
        p_good_type: "",
        p_good_name: "",
        p_good_img: "",
        pgNo: "",
        arrival_time: "",
        budget_price: "0.00",
        num: "0",
        brand_id: [],
        cat_id: [],
        unit: [],
        good_img: "",
        good_name: "",
        total_weight: "0",
        is_addrs: "",
        is_custom: "",
        is_gold_price: "",
        config: [],
        specs_weight: "0.000",
        other_config: "",
        cost_desc: "",
        use_desc: "",
        remark: "",
        metal_id: "",
        gold_price: "",
        area:""
      },
      rulesThis: this.rules,
      // 验证规则
      rules: edutRules,
    };
  },
  computed: {
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "zixunOrderDetail"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  mounted() {
    this.initForm();
  },
  watch: {
    id: function (val) {
      if (val) {
        this.initForm();
      }
    },
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  methods: {
    priceAccMul(a, b) {
      return accMul(a, b);
    },
    async initForm() {
      this.loading = true;
      this.status = "";
      this.spec_tableData = [];
      this.platform_name = "";
      this.rulesThis = this.rules;
      this.disabled = false;
      await this.resetForm();
      this.sch_is_noble();
      this.getNewTime();
      this.loading = false;
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async digitalInput(e, key) {
      this.ruleForm[key] = e + "" || "0";
      this.$refs.ruleForm.validateField(key);
    },
    areasearchChange(e) {
      const { id, label } = e
      this.areaCode = e && id ? [id] : []
      this.ruleForm.area = label
      this.$refs.ruleForm.validateField('area')
    },
    sch_is_noble() {
      this.rulesThis["projectNo"][0].required = this.ruleForm.is_project === "1";
      this.$refs.ruleForm.validateField("projectNo");
      let list = [
        "config",
        "specs_weight",
        "is_gold_price",
        "metal_id",
        "other_config",
        "gold_price",
      ];

      for (let i = 0; i < list.length; i++) {
        if (this.rulesThis[list[i]]) {
          this.rulesThis[list[i]][0].required = this.is_noble;
          // console.log(list[i] + "===" + this.rulesThis[list[i]][0].required);
          this.$refs.ruleForm.validateField(list[i]);
        }
      }
    },

    async resetForm() {
      this.resign_name = "";
      this.hand_name = "";
      this.status = "";

      // { value: "0", label: "非项目" },
      // { value: "1", label: "项目" },
      // 重置
      await this.$nextTick(async () => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          let {
            is_project, //竞价类型 1销售2竞价，
            projectNo, //项目编号
            khNo, //客户编号
            khname, //客户名称
            companyNo,
            endtime, //竞价截止时间
            platform_code, //平台id
            platform_name,
            pay_id,
            pay_name,
            ladder,
            pgNo,
            can,
            arrival_time,
            budget_price,
            num,
            brand_id,
            brand,
            cat_id,
            good_img,
            good_name,
            total_weight,
            is_addrs,
            is_custom,
            is_gold_price,
            config,
            specs_weight,
            other_config,
            cost_desc,
            use_desc,
            remark,
            metal_id,
            gold_price,
            unit,
            unit_name,
            p_cat_info,
            p_cat_id,
            p_budget_price,
            p_pgNo,
            p_num,
            p_good_type,
            p_good_name,
            p_good_img,
            p_arrtime,
            specinfo,
            enclosure_file,
            area
          } = JSON.parse(JSON.stringify(this.sitem));

          this.unit_name = unit_name;
          this.brand_name = brand;
          this.spec_tableData =
            specinfo && specinfo.length > 0 ? JSON.parse(JSON.stringify(specinfo)) : [];
          this.cat_id_name = "";

          //非项目 projectNo不必填
          if(this.sitem.is_project === '0'){
            this.$set(this.rulesThis.projectNo, '0', {
               required: false,
               message: '请选择项目',
               trigger: 'change'
            })
          }

          if (can && can.length > 0) {
            can.forEach((s, i) => {
              if (i === 0 && s.id === "6") {
                this.is_noble = true;
              }
              this.cat_id_name += i === 0 ? s.name : `_${s.name}`;
            });
          }
          // console.log(pgNo);
          let fi = "-1";
          this.platform_name = platform_name || "";
          this.ruleForm = {
            infoNo: this.id,
            is_project: is_project || "0", //竞价类型 1销售2竞价，
            projectNo: projectNo || "", //项目编号
            khNo: khNo ? [khNo] : [], //客户编号
            khname: khname ? [khname] : [], //客户名称
            companyNo: companyNo || this.business_companyNo || "",
            endtime: endtime || "", //竞价截止时间
            platform_code: platform_code || "", //平台id
            pay_id: pay_id || "0",
            puse_desc: "",
            budget_total: "",
            arrtime: "",
            p_cat_info: p_cat_info,
            p_cat_id: p_cat_id,
            p_budget_price: p_budget_price,
            p_pgNo: p_pgNo,
            p_num: p_num,
            p_good_type: p_good_type,
            p_good_name: p_good_name,
            p_good_img: p_good_img,
            p_arrtime: p_arrtime,
            pgNo: pgNo || "",
            arrival_time: arrival_time || "",
            budget_price: budget_price || "0.00",
            num: num || "0",
            brand_id: brand_id ? [brand_id] : [],
            cat_id: cat_id && cat_id.length > 0 ? [cat_id[cat_id.length - 1]] : [],
            good_img: good_img || "",
            good_name: good_name || "",
            total_weight: total_weight || "0",
            is_addrs: is_addrs || "0",
            is_custom: is_custom || "0",
            is_gold_price: is_gold_price || "0",
            config: config ? config.split(",") : [],
            specs_weight: specs_weight || "0.000",
            other_config: other_config || "",
            cost_desc: cost_desc || "",
            use_desc: use_desc || "",
            remark: remark || "",
            metal_id: metal_id || "",
            gold_price: gold_price || "",
            unit: unit ? [unit] : [],
            enclosure_file: enclosure_file || "",
            area
          };

          this.areaLabel = area ? [area] : []

          // console.log(this.ruleForm)
          this.pay_name = pay_id + "" == "0" ? "不选择" : pay_name;
          if (this.ruleForm.projectNo) {
            await this.projectChange([{ projectNo: this.ruleForm.projectNo }]);
          }

          this.od_form = JSON.parse(JSON.stringify(this.ruleForm));
          await this.set_must_spec();
        }
      });
    },
    //项目选择
    async projectChange(e) {
      const key = e && e.length > 0 ? e[0].projectNo : "";
      if (key) {
        const { code, data, message } = await asyncRequest.pdetail({
          projectNo: key,
        });
        if (code === 0) {
          const {
            khNo,
            khName,
            pay_id,
            pay_name,
            platform_id,
            platform_name,
            ladder,
            companyNo,
            company,
          } = data;

          this.companyName = company
          this.ruleForm.projectNo = key;
          this.projectSitem = JSON.parse(JSON.stringify(data));
          //平台赋值
          this.platform_code_codesearchChange({
            id: platform_id,
            code: platform_id,
            label: platform_name,
          });
          //支付渠道赋值
          this.pay_id_change({
            id: pay_id,
            code: pay_id,
            label: pay_id + "" == "0" ? "不选择" : pay_name,
          });
          //销售方公司赋值
          this.company_idsearchChange({
            id: companyNo,
            code: companyNo,
            label: company,
          });
          //购买方公司赋值
          this.customerChange({
            id: khNo,
            code: khNo,
            label: khName,
          });
          this.ptableData = ladder;
          this.ptableData.forEach((e) => {
            e.cat_name = "";
            const { cat_info } = e;
            if (cat_info && cat_info.length > 0) {
              cat_info.forEach((b, bi) => {
                e.cat_name += bi !== 0 ? "/" + b.name : b.name;
              });
            }
          });
          this.tableData = [];
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(message);
          this.ptableData = [];
          this.ruleForm.use_desc = "";
          this.ruleForm.budget_total = "";
          this.ruleForm.arrtime = "";
          this.tableData = [];
        }
      }
    },
    openEdit(index, sitem) {
      this.modelIndex = index;
      this.modelSitem = sitem;
      this.showOtherModel = true;
    },
    openDelete(index) {
      this.spec_tableData.splice(index, 1);
    },
    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);
        });
      }
    },
    //规格编辑修改结果
    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 submitForm() {
      this.sch_is_noble();
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.spec_tableData.length === 0) {
            this.$message.warning("请选择商品规格！");
            return;
          }
          let isok = true;
          // console.log(this.spec_tableData);
          this.spec_tableData.forEach((si, sii) => {
            if (si.spec_value_id === "") {
              isok = false;
            }
          });
          if (!isok) {
            this.$message.warning("请选择商品规格值缺失！");
            return;
          }
          if (this.loading) return;
          this.loading = true;
          let model = JSON.parse(JSON.stringify(this.ruleForm));
          const { pendtime, is_project, endtime } = model;
          if (
            is_project === "1" &&
            new Date(endtime).getTime() > new Date(pendtime).getTime()
          ) {
            this.$message.warning("竞价截止时间不能晚于项目竞价截止时间！");
            this.loading = false;
            return;
          }
          if (new Date(endtime).getTime() <= new Date().getTime()) {
            this.$message.warning("竞价截止时间应该大于当前时间！");
            this.loading = false;
            return;
          }
          model.khNo = model.khNo.toString();
          // model.platform_code = model.platform_code.toString();
          model.brand_id = model.brand_id.toString();
          model.unit = model.unit.toString();
          model.cat_id = model.cat_id.toString();
          model.config = model.config.toString();
          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);
          });

          delete model["pendtime"];
          delete model["arrtime"];
          delete model["puse_desc"];
          delete model["budget_total"];
          delete model["khname"];

          this.loading = false;
          const isCopy = this.type === 'copy-edit'
          const api =  isCopy ? asyncRequest.add : asyncRequest.update
          
          if(isCopy){
            const rootPropertys = ['is_project','endtime','platform_code','platform_code','khNo','companyNo']
            const ladderItem = {}
            Object.keys(model).forEach(key => {
              if(!rootPropertys.includes(key)){
                ladderItem[key] = model[key]
                delete model[key]
              }
            })

            model['ladder'] = []
            model['ladder'][0] = ladderItem
          }

          model.area = this.ruleForm.area
          const res = await api(model)
          this.loading = false;
          if (res && res.code === 0) {
            this.$notify.success({
              title: "创建成功！",
              message: "",
            });
            this.$emit("refresh", true);
          } 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;
        }
      });
    },

    //支付渠道选择
    pay_id_change(e) {
      const { id, code, label } = e;
      this.ruleForm.pay_id = id || "";
      this.pay_name = label || "";
      this.$refs.ruleForm.validateField("pay_id");
    },
    //平台选择
    platform_code_codesearchChange(e) {
      const { id, code, label } = e;
      this.ruleForm.platform_code = id || "";
      this.$refs.ruleForm.validateField("platform_code");
    },
    //品牌选择
    brand_id_searchChange(e) {
      const { id } = e;
      this.ruleForm.brand_id = id ? [id] : [];
      this.$refs.ruleForm.validateField("brand_id");
    },
    unitsearchChange(e) {
      const { code, label } = e;
      this.ruleForm.unit = code ? [code] : [];
      this.unit_name = label || "";
      this.$refs.ruleForm.validateField("unit");
    },
    //销售方公司选择
    company_idsearchChange(e) {
      const { id, code, label } = e;
      this.ruleForm.companyNo = code || "";
      this.$refs.ruleForm.validateField("companyNo");
    },
    //购买方公司选择
    customerChange(e) {
      const { id, code, label, area } = e;
      this.ruleForm.khNo = code ? [code] : [];
      this.ruleForm.customer_name = label ? label : "";
      this.areaLabel = area && area !== '不限区域' ? [area] : []
      this.$refs.ruleForm.validateField("khNo");
    },
    //贵金属种类选择
    noble_metalsearchChange(e) {
      const { id, price } = e;
      this.ruleForm.metal_id = id ? id : "";
      this.$refs.ruleForm.validateField("noble_metal");
      this.ruleForm.gold_price = price ? price : "0";
      this.$refs.ruleForm.validateField("gold_price");
    },
    //商品分类选择
    async goods_class_change(e) {
      const { code, pid, id, label, item } = e;
      this.ruleForm.cat_id = id ? [id] : [];
      this.ruleForm.cat_arr_id = item;
      this.$refs.ruleForm.validateField("cat_id");
      this.is_noble = pid === "6";
    },
    //判断图片规格
    beforeAvatarUpload(file) {
      let isJPG = false,
        isLt2M = false;
      if (file) {
        if (
          file.type === "image/jpg" ||
          file.type === "image/png" ||
          file.type === "image/jpeg"
        ) {
          isJPG = true;
        }
        isLt2M = file.size / 1024 / 1024 < 1;
        if (!isJPG) {
          this.$message.error("图片格式不正确！");
        }
        if (!isLt2M) {
          this.$message.error("图片大小不能超过 1MB!");
        }
      }

      return isJPG && isLt2M;
    },
    //图片上传失败
    UploadErrorEvent(res) {
      if (res !== "break") {
        this.$message.error("图片上传失败!");
        this.ruleForm.good_img = "";
        this.$refs.ruleForm.validateField("good_img");
      }
    },
    //图片上传成功
    async UploadSuccessEvent(data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.good_img = url;
        this.$message.success("图片上传成功!");
        this.$refs.ruleForm.validateField("good_img");
      }
    },
    //其他文件上传失败
    UploadErrorOtherenclosure_file(res) {
      if (res !== "break") {
        this.$refs.ruleForm.validateField("enclosure_file");
      }
    },

    //判断其他文件规格
    beforeOtherUpload(file) {
      let isJPG = false;
      if (
        file.type === "application/msword" ||
        file.type ===
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
        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;
    },

    deleteUrl() {
      this.ruleForm.enclosure_file = "";
      this.$refs.ruleForm.validateField("enclosure_file");
    },
    // 其他文件上传成功
    async UploadSuccessOtherenclosure_file(data) {
      const { url } = data;
      if (url === "noToken") {
        await this.logout();
      } else {
        this.ruleForm.enclosure_file = url;
        this.$message.success("附件上传成功!");
      }
    },
    getNewTime() {
      this.fnewTime = new Date().valueOf();
    },
  },
};
</script>

<style lang="scss" scoped>
.lsac {
  font-weight: bold;
  font-size: 14px;
  // position: absolute;
  color: #777;
  // top: 0;
  // right: 0;
}
</style>
