<template>
  <div class="goodsOnlineAdd">
    <div class="goodsOnlineAdd-main" v-if="powers.some((i) => i == '007')">
      <el-form
        status-icon
        :model="ruleForm"
        :rules="rulesThis"
        ref="ruleForm"
        :size="'mini'"
        v-loading="loading"
        label-width="110px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="8">
            <!-- :platformType="ruleForm.platform_type" -->

            <el-form-item label="所属平台" prop="platform">
              <search-terrace
                :value="ruleForm.platform"
                :size="'mini'"
                :is_show="'1'"
                :isDetail="false"
                :placeholder="'所属平台'"
                @searchChange="platform_codesearchChange"
              />
            </el-form-item>

            <el-form-item label="对接平台" prop="platform_type">
              <el-select
                placeholder="对接平台"
                style="width:100%"
                v-model="ruleForm.platform_type"
                @change="handleTypeChange"
                disabled
              >
                <el-option label="BBC" value="2" />
                <el-option label="有赞平台" value="1" />
                <el-option label="无对接" value="0" />
              </el-select>
            </el-form-item>

            <el-form-item label="定价模式" prop="is_fixed">
              <el-select v-model="ruleForm.is_fixed" style="width:100%" placeholder="定价模式">
                <el-option
                  v-for="f in fixedOptions"
                  :key="f.value"
                  :value="f.value"
                  :label="f.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="上线原因" prop="online_reason">
              <el-input
                :disabled="false"
                placeholder="上线原因"
                v-model="ruleForm.online_reason"
                maxlength="200"
              />
            </el-form-item>

            <el-form-item label="上线备注" prop="online_remark">
              <el-input
                type="textarea"
                :rows="3"
                :disabled="false"
                placeholder="上线备注"
                maxlength="250"
                show-word-limit
                v-model="ruleForm.online_remark"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-table :data="tableData" stripe border :size="'mini'" style="width: 100%">
              <el-table-column width="50" type="index" show-overflow-tooltip />
              <el-table-column prop="spuCode" label="商品编号" width="180" show-overflow-tooltip />
              <el-table-column prop="good_thumb_img" label="图片" width="45" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div
                    v-if="scope.row.good_thumb_img"
                    style="width: 20px; height: 20px"
                    class="hover"
                    v-viewer
                  >
                    <img
                      :src="scope.row.good_thumb_img"
                      style="display: inline-block; width: 100%; height: 100%"
                      alt
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="good_name" label="商品名称" min-width="160" show-overflow-tooltip />
              <el-table-column prop="cat_name" label="分类" min-width="110" show-overflow-tooltip />
              <el-table-column
                prop="good_name"
                label="品牌"
                min-width="brand_name"
                show-overflow-tooltip
              />
              <el-table-column prop="good_type" label="来源" min-width="110" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-tag
                    :size="'mini'"
                    :type="scope.row.create_source == '1' ? 'warning' : ''"
                    v-text="scope.row.create_source === '1' ? '咨询成交商品' : '手动创建商品'"
                  ></el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="good_type" label="是否定制" min-width="70" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-tag
                    :size="'mini'"
                    :type="scope.row.good_type == '1' ? '' : 'warning'"
                    v-text="
                      (options1.find((item) => item.id == scope.row.status) || {}).name ||
                      '--'
                    "
                  ></el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="supplierNo" label="供应商编号" width="110" show-overflow-tooltip />
              <el-table-column
                prop="supplier_name"
                label="供应商名称"
                width="110"
                show-overflow-tooltip
              />
              <el-table-column prop="companyNo" label="业务公司编号" width="110" show-overflow-tooltip />
              <el-table-column prop="company" label="业务公司名称" width="110" show-overflow-tooltip />

              <el-table-column label="京东链接" min-width="120px">
                <template slot-scope="scope">
                  <el-input size="mini" placeholder="京东比价链接" :value="tableData[scope.$index].market_url" @input="changeMarketUrlByIndex($event,scope.$index)" />
                </template>
              </el-table-column>

              <el-table-column fixed="right" width="70px">
                <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="showModel = true"
                    />
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-tooltip effect="dark" content="删除" placement="top">
                    <i class="el-icon-delete tb-icon" @click="openDel(scope.$index)"></i>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <!--添加商品-->
            <search-good-modal
              :is-noble="isNoble"
              :is-consult="isConsult"
              :check-type="true"
              :showModel="showModel"
              :once="false"
              @resultList="resultList"
              @cancel="showModel = false"
            />
          </el-col>
          <el-col :span="24" style="text-align: right; padding: 15px 0 15px 0">
            <el-button :size="'mini'" type="primary" @click="submitForm">保 存</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/goodStore/goodsOnline";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import searchGoodModal from "@/components/search-good-modal";
import { rules, options1 } from "./columns";
import { replaceTextWrapAndSpace } from "@/utils";
export default {
  name: "goodsOnlineAdd",
  mixins: [resToken],
  props: [
      "showModel", 
      "sitem",
      "type", 
      "id"
    ],
  components: {
    searchGoodModal
  },
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    isFixed() {
      // 非咨询商品 && 非有赞平台 && 贵金属开启实时金价
      return (
        !this.isConsult &&
        !this.isYzPlatform &&
        this.isNoble &&
        this.ruleForm.platform_type !== "1"
      );
    },
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          item => item.menu_route == "goodsOnlineAdd"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    fixedOptions() {
      return [
        { value: "1", label: "一口价" },
        ...(this.isFixed ? [{ value: "0", label: "实时金价" }] : [])
      ];
    }
  },
  watch: {
    newTime: function(val) {
      if (val) {
        this.initForm();
      }
    },
    isFixed() {
      if (this.ruleForm.is_fixed === "0") {
        this.ruleForm.is_fixed = "";
      }
    }
  },
  data() {
    return {
      isNoble: null,
      isConsult:null,
      tableData: [],
      costshowModel: false,
      costmodelIndex: "",
      costsitem: {},
      showModel: false,
      status: "",
      rulesThis: {
        ...this.rules,
        platform_type: [
          {
            required: true,
            message: "请选择对接平台",
            trigger: "change"
          }
        ]
      },
      activeName: "1",
      isYzPlatform: false,
      loading: true,
      //是否定制
      options1: options1,
      ruleForm: {},
      rules: rules
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    handleTypeChange(){
      this.ruleForm.platform = ''
    },
    async initForm() {
      this.loading = true;
      console.log(this.resetFormData)
      this.resetFormData();
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    openDel(index) {
      this.tableData.splice(index, 1);
      this.isConsult = this.tableData.length === 0 ? null : this.isConsult;
      this.isNoble = this.tableData.length === 0 ? null : this.isNoble;
    },
    changeMarketUrlByIndex(market_url,index){
      console.log(market_url)

      this.$set(this.tableData,index,{
        ...this.tableData[index],
        market_url
      })
    },
    resultList(e, {isNoble, isConsult}) {
      this.showModel = false;
      let list = JSON.parse(JSON.stringify(e));
      let oldList = JSON.parse(JSON.stringify(this.tableData));

      this.isNoble = isNoble;
      this.isConsult = isConsult;

      list.forEach((e, ei) => {
        let index = oldList.findIndex(a =>e.spuCode === a.spuCode);
        if(index !== -1) return
        let item = JSON.parse(JSON.stringify(list[ei]));
        this.tableData.push({...item, market_url:"" });
      });
    },
    async submitForm() {
      this.ruleForm.online_remark = replaceTextWrapAndSpace(
        this.ruleForm.online_remark
      );


      if(this.tableData.length > 0){
        const regex = /^(http|https):\/\/[^ "]+$/;
        for(let index = 0;index < this.tableData.length;index ++){
          const item = this.tableData[index];
          const line = index + 1;
          if(!item.market_url){
            this.$message.warning(`商品第 ${line} 行,京东链接不能为空`)
            return
          }

          if(!regex.test(item.market_url)){
            this.$message.warning(`商品第 ${line} 行,京东链接格式不正确`)
            return
          }
        }
      }

      await this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (!this.loading) {
            if (this.tableData.length === 0) {
              this.$message.warning("至少选择一个商品！");
              return;
            }
            if (this.tableData.length > 100) {
              this.$message.warning("商品数量不能超过100！");
              return;
            }

            this.loading = true;
            let model = JSON.parse(JSON.stringify(this.ruleForm));
            model.goodinfo = []
            let list = JSON.parse(JSON.stringify(this.tableData));
            list.forEach(e => {
              model.goodinfo.push({
                spuCode: e.spuCode,
                market_url: e.market_url
              })
            });
            delete model.codes;
            const { code, data, message } = await asyncRequest.add(model);
            this.loading = false;
            if (code === 0) {
              this.$notify.success({
                title: "新建成功",
                message: ""
              });
              this.showModelThis = false;
              // 刷新
              this.routeReGoto("goodsOnline", {});
            } else if (code >= 100 && code <= 104) {
              await this.logout(code <= 104);
            } else if (message === "一口价商品请先完善商品成本单价") {
              this.$message.warning(message);
            } else if (code === 1004) {
              this.open_show(
                data,
                "以下商品的业务公司和平台支付渠道中的业务公司重复，不允许上线"
              );
            } else if (code === 1009) {
              this.open_show(data, "以下商品已申请过商品上线");
            } else if (code === 1010) {
              this.open_show(data, "该平台要求商品必须要有一件的成本！");
            } else {
              this.$message.warning(message);
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    open_show(data, title) {
      const resList = JSON.parse(JSON.stringify(data));
      let htmlList = "<ul>";
      resList.forEach(v => {
        htmlList += `<li>
                  <span>${v.good_name}</span></li>`;
      });
      htmlList += "</ul>";
      this.$notify({
        title: title,
        dangerouslyUseHTMLString: true,
        message: htmlList
      });
    },
    resetFormData() {
      this.ruleForm = {
        platform_type: "",
        is_fixed: "",
        platform: "", //string	平台id
        codes: [], //string	无
        online_reason: "", //string	上线原因
        online_remark: "" //string	上线备注
      };
      this.tableData = [];
    },
    async resetForm() {
      // 重置
      await this.$nextTick(async () => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.resetFormData();
        }
      });
    },

    platform_codesearchChange(e) {
      const { id,platform_type } = e;
      this.ruleForm.platform = id || "";
      this.isYzPlatform = String(platform_type) === "1";

      this.ruleForm.platform_type = platform_type
      this.$refs.ruleForm.validateField("platform");
    }
  }
};
</script>
<style lang="scss" scoped>
.goodsOnlineAdd {
  .goodsOnlineAdd-main {
    padding: 30px 20px 0 20px;
  }
}
</style>
