<template>
  <el-dialog
    v-loading="loading"
    :title="'添加商品上线'"
    :center="true"
    align="left"
    top="8vh"
    width="1040px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="showModelThis = false"
  >
    <el-card style="margin: -20px 0 0 0; padding-bottom: 0">
      <el-row :gutter="10">
        <el-col :span="24" style="padding: 0 0 15px 0">
          <el-table
            :data="list"
            stripe
            :size="'mini'"
            border
            max-height="380px"
            style="width: 100%"
          >
            <el-table-column prop="spuCode" label="编号" width="160" 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"
                  v-viewer
                  style="width: 20px; height: 20px"
                  class="hover"
                >
                  <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="160px" show-overflow-tooltip />
            <el-table-column prop="cat_name" label="分类" min-width="100" show-overflow-tooltip />
            <el-table-column prop="brand_name" label="品牌" show-overflow-tooltip />
            <el-table-column prop="good_type" label="定制" width="50" 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 ||
                      '--'
                  "
                />
              </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 prop="market_url" label="京东链接" width="200" fixed="right" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input size="mini" placeholder="京东比价链接" :value="list[scope.$index].market_url" @input="changeMarketUrl($event,scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :rules="rulesThis"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-row style="padding-bottom">
              <el-col :span="8">
                <el-form-item label="所属平台" prop="platform">
                  <search-terrace
                    :is_show="'1'"
                    :is-detail="false"
                    :placeholder="'所属平台'"
                    :value="ruleForm.platform"
                    :platformType="ruleForm.platform_type"
                    @searchChange="platform_codesearchChange"
                  />
                </el-form-item>

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

                <el-form-item label="定价模式" prop="is_fixed">
                  <el-select v-model="ruleForm.is_fixed" style="width:100%">
                    <el-option
                      v-for="p in pricingOptions"
                      :key="p.value"
                      :value="p.value"
                      :label="p.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="16" style="text-align: right">
                <!-- <el-form-item label="京东链接" prop="market_url">
                  <el-input
                    v-model="ruleForm.market_url"
                    :disabled="false"
                    placeholder="京东比价链接"
                    maxlength="200"
                  />
                </el-form-item> -->

                <el-form-item label="上线原因" prop="online_reason">
                  <el-input
                    v-model="ruleForm.online_reason"
                    :disabled="false"
                    placeholder="上线原因"
                    maxlength="200"
                  />
                </el-form-item>

                <el-form-item label="上线备注" prop="online_remark">
                  <el-input
                    v-model="ruleForm.online_remark"
                    type="textarea"
                    :rows="3"
                    :disabled="false"
                    placeholder="商品备注"
                    maxlength="2000"
                    show-word-limit
                  />
                </el-form-item>
                <el-button v-if="id !== '007'" type="primary" :size="'mini'" @click="submitForm">保 存</el-button>
                <el-button :size="'mini'" @click="showModelThis = false">
                  {{
                  id == "007" ? "关 闭" : "取 消"
                  }}
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/goodStore/goodsCost";
import { replaceTextWrapAndSpace } from "@/utils";
import resToken from "@/mixins/resToken";
export default {
  name: "Brand",
  mixins: [resToken],
  props: ["showModel", "id", "sitem", "isNobleMetal", "isConsultFlag"],
  data() {
    return {
      loading: false,
      isYZPlatform: false,
      showModelThis: this.showModel,
      ruleForm: {
        list:[],
        platform_type: "",
        platform: "", // string	平台id
        is_fixed: "", // string 定价模式
        online_reason: "", // string	上线原因
        online_remark: "" // string	上线备注
      },
      // 是否定制
      options1: [
        { id: "0", name: "否" },
        { id: "1", name: "是" }
      ],
      rulesThis: this.rules,
      rules: {
        platform: [
          {
            required: true,
            message: "请选择所属平台",
            trigger: "change"
          }
        ],
        is_fixed: [
          {
            required: true,
            message: "请选择定价模式",
            trigger: "change"
          }
        ],
        platform_type: [
          {
            required: true,
            message: "请选择对接平台",
            trigger: "change"
          }
        ],
        online_reason: [
          {
            required: true,
            message: "上线原因不能为空",
            trigger: "blur"
          }
        ],
        online_remark: [
          {
            required: true,
            message: "上线备注不能为空",
            trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    isFixed() {
      /** 选择实时金价条件：非有赞平台&非咨询成交商品&贵金属商品 */
      return !this.isYZPlatform && !this.isConsultFlag && this.isNobleMetal && this.ruleForm.platform_type !== "1" 
    },
    pricingOptions() {
      return [
        { value: "1", label: "一口价" },
        ...(this.isFixed ? [{ value: "0", label: "实时金价" }] : [])
      ];
    }
  },
  watch: {
    isFixed() {
      if (this.ruleForm.is_fixed === "0") {
        this.ruleForm.is_fixed = "";
      }
    },
    showModel: function(val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
        this.list = JSON.parse(JSON.stringify(this.sitem));
      }
    },
    showModelThis(val) {
      if (!val) { this.$emit("cancel");}
    }
  },
  methods: {
    changeMarketUrl(market_url,index){
      this.$set(this.list,index,{ ...this.list[index], market_url })
    },
    async initForm() {
      this.loading = true;
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            platform_type: "",
            platform: "", // string	平台id
            online_reason: "", // string	上线原因
            online_remark: "" // string	上线备注
          };
        }
      });
    },
    platform_codesearchChange(e) {
      const { id, platform_type } = e;
      this.ruleForm.platform = id || "";
      this.isYZPlatform = platform_type === "1";
      this.ruleForm.platform_type = platform_type
      this.$refs.ruleForm.validateField("platform");
    },
    async submitForm() {
      this.ruleForm.online_remark = replaceTextWrapAndSpace(
        this.ruleForm.online_remark
      );

      if(this.list.length > 0){
        const regex = /^(http|https):\/\/[^ "]+$/;
        for(let index = 0;index < this.list.length;index ++){
          const item = this.list[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) {
            this.loading = true;
            const model = JSON.parse(JSON.stringify(this.ruleForm));

            // model.platform = model.platform.toString();
            model.codes = [];
            const list = JSON.parse(JSON.stringify(this.list));
            model.goodinfo = []
            list.forEach(e => {
              model.goodinfo.push({
                spuCode: e.spuCode,
                market_url:e.market_url
              });
            });

            delete model.codes;

            const { code, data, message } = await asyncRequest.online_add(
              model
            );
            this.loading = false;
            if (code === 0) {
              this.$notify.success({
                title: "已成功添加至上线流程！",
                message: ""
              });
              this.showModelThis = false;
              // 刷新
              this.$emit("refresh");
            } else if (code >= 100 && code <= 104) {
              await this.logout();
            } 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 {
          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
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.brand {
}
</style>
