<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">
            <el-form-item label="所属平台" prop="platform">
              <search-terrace
                :value="ruleForm.platform"
                :disabled="false"
                :size="'mini'"
                :is_show="'1'"
                :isDetail="false"
                :placeholder="'所属平台'"
                @searchChange="platform_codesearchChange"
              />
            </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-form-item label="上线原因" prop="online_reason">
              <el-input
                :disabled="false"
                placeholder="上线原因"
                v-model="ruleForm.online_reason"
                maxlength="200"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <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="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 fixed="right">
                <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"
              :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", "id", "type", "sitem"],
  components: {
    searchGoodModal
  },
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    isFiexed() {
      return !this.isYzPlatform && this.isNoble;
    },
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          item => item.menu_route == "goodsOnlineAdd"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    fixedOptions() {
      return [
        { value: "1", label: "一口价" },
        ...(this.isFiexed ? [{ value: "0", label: "实时金价" }] : [])
      ];
    }
  },
  watch: {
    newTime: function(val) {
      if (val) {
        this.initForm();
      }
    },
    isFiexed() {
      if (this.ruleForm.is_fixed === "0") {
        this.ruleForm.is_fixed = "";
      }
    }
  },
  data() {
    return {
      isNoble: null,
      tableData: [],
      costshowModel: false,
      costmodelIndex: "",
      costsitem: {},
      showModel: false,
      status: "",
      rulesThis: this.rules,
      activeName: "1",
      isYzPlatform: false,
      loading: true,
      //是否定制
      options1: options1,
      ruleForm: {},
      rules: rules
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.resetFormData();
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },

    openDel(index) {
      this.tableData.splice(index, 1);
      if (this.tableData.length === 0) {
        this.isNoble = null;
      }
    },
    resultList(e) {
      this.showModel = false;
      let list = JSON.parse(JSON.stringify(e));
      let oldList = JSON.parse(JSON.stringify(this.tableData));

      const categoryIds = list.map(({ cat_info, is_gold_price }) => ({
        id: String(cat_info[0].id),
        isGoldPrice: String(is_gold_price)
      }));

      const nobleIds = categoryIds.filter(
        ({ id, isGoldPrice }) => id === "6" && isGoldPrice === "1"
      );

      console.log(nobleIds, categoryIds);

      this.isNoble =
        nobleIds.length > 0 && categoryIds.length === nobleIds.length;

      list.forEach((e, ei) => {
        let index = oldList.findIndex(a => {
          return e.spuCode === a.spuCode;
        });

        if (index === -1) {
          let item = JSON.parse(JSON.stringify(list[ei]));
          this.tableData.push(item);
        }
      });
    },
    async submitForm() {
      this.ruleForm.online_remark = replaceTextWrapAndSpace(
        this.ruleForm.online_remark
      );
      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));
            let list = JSON.parse(JSON.stringify(this.tableData));
            list.forEach(e => {
              model.codes.push(e.spuCode);
            });
            // model.platform = model.platform.toString();
            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 = {
        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, code, label, platform_type } = e;
      this.ruleForm.platform = id || "";
      this.isYzPlatform = String(platform_type) === "1";
      this.$refs.ruleForm.validateField("platform");
    }
  }
};
</script>
<style lang="scss" scoped>
.goodsOnlineAdd {
  .goodsOnlineAdd-main {
    padding: 30px 20px 0 20px;
  }
}
</style>
