<template>
  <div class="activeAdd">
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rulesThis"
      ref="ruleForm"
      :size="'mini'"
      label-width="90px"
      class="demo-ruleForm"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="业务企业" prop="company_id">
            <search-work-company
              :value="ruleForm.company_id"
              :disabled="status !== ''"
              :size="'mini'"
              :isDetail="false"
              :placeholder="'业务企业'"
              @searchChange="company_idsearchChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="活动标题" prop="activity_name">
            <el-input
              placeholder="活动标题"
              :disabled="status !== ''"
              v-model="ruleForm.activity_name"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属平台" prop="platform_code">
            <search-terrace
              :value="ruleForm.platform_code"
              :disabled="status !== ''"
              :size="'mini'"
              :isDetail="false"
              :is_show="start !== '' ? '1' : '0'"
              :placeholder="'所属平台'"
              @searchChange="platform_codesearchChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="活动时间" required style="margin: 0">
            <el-row>
              <el-col :span="11">
                <el-form-item prop="datactivity_name">
                  <el-date-picker
                    type="datetime"
                    placeholder="开始时间"
                    :disabled="status !== ''"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="pickerOptions1"
                    v-model="ruleForm.activity_start"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col class="tc" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item prop="activity_end">
                  <el-date-picker
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="结束时间"
                    :disabled="status !== ''"
                    :picker-options="pickerOptions2"
                    v-model="ruleForm.activity_end"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库存类型" prop="is_stock">
            <el-select
              v-model="ruleForm.is_stock"
              style="width: 100%"
              :size="'mini'"
              :disabled="status !== ''"
              placeholder="库存类型"
              @change="is_stock_change"
            >
              <el-option
                v-for="item in is_stock"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="活动描述" prop="activity_desc">
            <el-input
              placeholder="活动描述"
              type="textarea"
              :rows="2"
              :disabled="status !== ''"
              show-word-limit
              v-model="ruleForm.activity_desc"
              maxlength="500"
            />
          </el-form-item>
        </el-col>
        <el-col
          :span="24"
          v-if="
            status == '4' ||
            !(
              (status === '0' && powers.some((i) => i == '056')) ||
              (status === '1' && powers.some((i) => i == '057')) ||
              (status === '2' && powers.some((i) => i == '058')) ||
              (status === '3' && powers.some((i) => i == '059'))
            )
          "
        >
          <el-form-item label="活动商品" :label-position="'top'" prop="good_list">
            <el-table
              :data="ruleForm.good_list"
              stripe
              border
              :size="'mini'"
              style="width: 100%"
            >
              <el-table-column
                prop="skuCode"
                label="商品编码"
                show-overflow-tooltip
                width="170"
              />
              <el-table-column prop="good_name" label="商品名称" show-overflow-tooltip />

              <template v-if="Number(sitem.status) > 3">
                <el-table-column prop="is_activity" label="是否使用活动价" width="110px">
                  <template slot-scope="scope">
                    <span>{{scope.row.is_activity === '1' ? '是' : '否'}}</span>
                  </template>
                </el-table-column>

                <el-table-column prop="settle_price" label="结算金额">
                  <template slot-scope="scope">
                    <span>{{scope.row.settle_price}}</span>
                  </template>
                </el-table-column>
              </template>

              <el-table-column prop="activity_stock" label="活动库存" width="180">
                <template slot-scope="scope">
                  <el-input-number
                    v-show="type !== 'view'"
                    style="width: 100%"
                    v-model="scope.row.activity_stock"
                    :min="1"
                    :max="100000000000"
                    :precision="0"
                    label="活动库存"
                  ></el-input-number>
                  <span v-show="type === 'view'">{{ scope.row.activity_stock }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="moq_num"
                label="起订量"
                width="100"
                v-if="!(status === '' || status === '0')"
                show-overflow-tooltip
              />
              <el-table-column
                prop="cost_price"
                label="成本单价(元)"
                width="100"
                v-if="!(status === '' || status === '0')"
                show-overflow-tooltip
              />
              <el-table-column
                v-if="!(status === '' || status === '0')"
                prop="sale_price"
                label="非活动价(元)"
                width="100"
                show-overflow-tooltip
              />
              <el-table-column
                v-if="!(status === '' || status === '0')"
                prop="activity_price"
                label="活动价(元)"
                width="100"
                show-overflow-tooltip
              />
              <el-table-column
                prop="status"
                label="审核状态"
                width="100"
                v-if="!(status === '' || status === '0')"
              >
                <template slot-scope="scope">
                  <el-tag
                    :size="'mini'"
                    :type="
                      scope.row.status == '0'
                        ? 'warning'
                        : scope.row.status == '2'
                        ? 'danger'
                        : ''
                    "
                    v-text="
                      (options.find((item) => item.value == scope.row.status) || {})
                        .label || '--'
                    "
                  ></el-tag>
                </template>
              </el-table-column>
              <el-table-column
                v-if="!(status === '' || status === '0')"
                prop="remark"
                label="审核备注"
                width="100"
                show-overflow-tooltip
              />
              <el-table-column fixed="right" width="80">
                <template slot="header" slot-scope="scope">
                  <span>操作</span>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    v-if="status === ''"
                    content="添加活动商品"
                    placement="top"
                  >
                    <i
                      class="el-icon-circle-plus-outline fr"
                      style="font-size: 18px; margin-top: 2px"
                      @click="openEdit('add', '0')"
                    />
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-tooltip effect="dark" content="查看商品信息" placement="top">
                    <i
                      class="el-icon-view tb-icon"
                      @click="showGoodModelFun(scope.row.skuCode)"
                    ></i>
                  </el-tooltip>
                  <el-tooltip
                    v-if="
                      (status + '' === '4' ||
                        status + '' === '5' ||
                        status + '' === '6') &&
                      powers.some((i) => i == '005')
                    "
                    effect="dark"
                    content="添加库存"
                    placement="top"
                  >
                    <i
                      class="el-icon-circle-plus-outline tb-icon"
                      @click="addStock(scope.$index)"
                    ></i>
                  </el-tooltip>
                  <el-tooltip
                    v-if="status === ''"
                    effect="dark"
                    content="删除"
                    placement="top"
                  >
                    <i
                      class="el-icon-delete tb-icon"
                      @click="openCostEditDelete(scope.$index)"
                    ></i>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <good-online-platform-modal
      :once="once"
      :sitem="ruleForm"
      :active="true"
      :show-model="showModel"
      :platform_type="platform_type"
      @resultList="resultList"
      @cancel="showModel = false"
    />
    <show-good-data-modal
      :show-model="showGoodModel"
      :skuCode="showGoodId"
      :spuCode="''"
      @cancel="showGoodModel = false"
    />
    <add-stock
      :show-model="addStockModel"
      :sitem="addStockSitem"
      @refresh="$emit('refresh', true)"
      @cancel="addStockModel = false"
    />
    <el-col
      :span="24"
      v-if="status === ''"
      style="text-align: right; padding: 15px 0 15px 0; border-top: 1px solid #dcdfe6"
    >
      <el-button :size="'mini'" type="primary" @click="submitForm">保 存 </el-button>
    </el-col>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/goodStore/active";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import goodOnlinePlatformModal from "@/components/good-online-platform-modal";
import showGoodDataModal from "@/components/show-good-data-modal";
import addStock from "./addStock";

export default {
  name: "activeAdd",
  mixins: [resToken],
  props: ["showModel", "id", "type", "sitem", "newTime"],
  components: {
    goodOnlinePlatformModal,
    showGoodDataModal,
    addStock,
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size", "business_companyNo"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find((i) => i.menu_route == "activeDetail") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      size: "small",
      activeName: "3",
      status: "",
      platform_type:"",
      options: [
        {
          value: "0",
          label: "待审核",
        },
        {
          value: "1",
          label: "通过",
        },
        {
          value: "2",
          label: "驳回",
        },
      ],
      is_stock: [
        { id: "0", name: "非库存品" },
        { id: "1", name: "库存品" },
      ],
      pickerOptions1: {
        disabledDate: (time) => {
          if (
            this.ruleForm.activity_end != null &&
            this.ruleForm.activity_end != "" &&
            time
          ) {
            return time.getTime() > new Date(this.ruleForm.activity_end).valueOf();
          }
        },
      },
      pickerOptions2: {
        disabledDate: (time) => {
          if (
            this.ruleForm.activity_start != null &&
            this.ruleForm.activity_start != "" &&
            time
          ) {
            return time.getTime() < new Date(this.ruleForm.activity_start).valueOf();
          }
        },
      },
      loading: false,
      showModel: false,
      once: false,
      rulesThis: this.rules,
      showGoodModel: false,
      showGoodId: "",
      addStockModel: false,
      addStockSitem: null,
      ruleForm: {},
      // 表格 - 数据
      tableData: [],
      rules: {
        activity_name: [
          {
            required: true,
            message: "活动标题不能为空",
            trigger: "blur",
          },
        ],
        company_id: [
          {
            required: true,
            message: "业务公司不能为空",
            trigger: "change",
          },
        ],
        platform_code: [
          {
            required: true,
            message: "所属平台不能为空",
            trigger: "change",
          },
        ],
        activity_start: [
          {
            required: true,
            message: "开始时间不能为空",
            trigger: "change",
          },
        ],
        activity_end: [
          {
            required: true,
            message: "结束时间不能为空",
            trigger: "change",
          },
        ],

        activity_desc: [
          {
            required: true,
            message: "活动描述不能为空",
            trigger: "blur",
          },
        ],
        is_stock: [
          {
            required: true,
            message: "请选择是否库存品",
            trigger: "change",
          },
        ],

        good_list: [
          {
            type: "array",
            required: true,
            message: "至少选择一个商品！",
            trigger: "change,blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.resetFormData();
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    async resetForm() {
      // 重置
      await this.$nextTick(async () => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.resetFormData();
        }
      });
    },
    //添加活动库存弹窗
    addStock(index) {
      this.addStockSitem = this.ruleForm.good_list[index];
      this.addStockSitem.actCode = this.sitem.activity_code;
      this.addStockModel = true;
    },
    showGoodModelFun(skuCode) {
      this.showGoodModel = true;
      this.showGoodId = skuCode;
    },
    openCostEditDelete(index) {
      this.ruleForm.good_list.splice(index, 1);
      this.$refs.ruleForm.validateField("good_list");
    },
    company_idsearchChange(e) {
      console.log(e);
      let old = this.ruleForm.company_id;
      if (e) {
        const { id, code, label } = e;
        this.ruleForm.company_id = code || "";
      }
      this.$refs.ruleForm.validateField("company_id");
      if (old !== this.ruleForm.company_id) {
        this.ruleForm.good_list = [];
      }
    },
    is_stock_change(e) {
      const { is_stock } = this.ruleForm;
      console.log(is_stock, e);
      let hs_is_stock = "0";
      if (this.ruleForm.good_list && this.ruleForm.good_list.length > 0) {
        hs_is_stock = this.ruleForm.good_list[0].is_stock;
      }
      if (is_stock !== hs_is_stock) {
        this.ruleForm.good_list = [];
      }

      console.log(this.ruleForm.good_list);
      //
    },
    platform_codesearchChange(e) {
      let old = this.ruleForm.platform_code;
      const { id, code, label ,platform_type} = e;
      this.ruleForm.platform_code = id || "";
      this.platform_type = platform_type;
      this.$refs.ruleForm.validateField("platform_code");
      let newList = this.ruleForm.platform_code;
      if (old !== newList) {
        this.ruleForm.good_list = [];
      }
    },
    resultList(e) {
      this.showModel = false;
      let list = JSON.parse(JSON.stringify(e));
      let oldList = JSON.parse(JSON.stringify(this.ruleForm.good_list));
      list.forEach((e, ei) => {
        let index = oldList.findIndex((a) => e.skuCode === a.skuCode);
        if (index === -1) {
          let item = JSON.parse(JSON.stringify(list[ei]));
          item.activity_stock = "1";
          item.newTime = new Date().valueOf();
          this.ruleForm.good_list.push({
            ...item,
            is_activity:'1',
            settle_price:'0.00'
          });
        }
      });
    },
    resetFormData() {
      this.tableData = [];
      const {
        activity_name,
        activity_desc,
        is_stock,
        end,
        start,
        platform_code,
        company_id,
        info,
        status,
      } = this.sitem;
      this.ruleForm = {
        activity_name: activity_name || "",
        platform_code: platform_code || "",
        company_id: company_id || this.business_companyNo || "",
        activity_start: start || "",
        activity_end: end || "",
        activity_desc: activity_desc || "",
        is_stock: is_stock || "",
        good_list: info && info.length > 0 ? JSON.parse(JSON.stringify(info)) : [],
      };
      this.status = status || "";
      this.tableData = info && info.length > 0 ? JSON.parse(JSON.stringify(info)) : [];
    },
    handleClick(row) {
      console.log(row);
    },
    openEdit() {
      const { company_id, platform_code, is_stock } = this.ruleForm;
      if (platform_code === "") {
        this.$message.warning("请选择平台！");
        return;
      }
      if (company_id === "") {
        this.$message.warning("请选择业务企业！");
        return;
      }
      if (is_stock === "") {
        this.$message.warning("请选择库存类型！");
        return;
      }
      this.showModel = true;
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (!this.loading) {
            this.loading = true;
            if (this.ruleForm.good_list.length === 0) {
              this.$message.warning("请选择活动商品信息！");
              this.loading = false;
              return;
            }
            let model = JSON.parse(JSON.stringify(this.ruleForm));

            const { good_list } = model;

            let list = JSON.parse(JSON.stringify(good_list));
            let newList = [];
            model.good_list = [];
            list.forEach((e) => {
              let item = {
                skuCode: e.skuCode,
                activity_stock: e.activity_stock
              };
              newList.push(item);
            });
            model.good_list = newList;
            let res = {};
            console.log(this.id, this.type);
            if (this.type === "add") {
              delete model["id"];
              delete model["spuCode"];
              res = await asyncRequest.add(model);
            } else {
              res = await asyncRequest.update(model);
            }
            console.log(res);
            this.loading = false;
            const { code, data, message } = res;
            if (code === 0) {
              const title = this.type === "add" ? "新建成功！" : "库存修改成功!";
              this.$notify.success({
                title: title,
                message: "",
              });
              this.showModelThis = false;
              // 刷新
              this.$emit("refresh", true);
            } else if (code >= 100 && code <= 104) {
              await this.logout();
            } else if (code == 1005) {
              let resList = JSON.parse(JSON.stringify(data));
              let htmlList = "<ul>";
              resList.forEach((v) => {
                htmlList += `<li>${v}</li>`;
              });
              htmlList += "</ul>";
              this.$notify({
                title: message,
                dangerouslyUseHTMLString: true,
                message: htmlList,
              });
            } else if (code == 1007) {
              let resList = JSON.parse(JSON.stringify(data));
              let htmlList = "<ul>";
              resList.forEach((v) => {
                htmlList += `<li>${v}</li>`;
              });
              htmlList += "</ul>";
              this.$notify({
                title: message,
                dangerouslyUseHTMLString: true,
                message: htmlList,
              });
            } else {
              this.$message.warning(message);
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // async initData() {
    //   this.loading = true;
    //   let res = await asyncRequest.detail({ id: this.id });
    //   this.loading = false;
    //   if (res.code === 0) {
    //     await this.resetForm(res.data);
    //   }
    // },
  },
};
</script>
<style lang="scss" scoped>
.activeAdd {
  .activeAdd-title {
    border-top: 1px solid #ebeef5;
    span {
      height: 50px;
      line-height: 50px;
      font-family: "微软雅黑", sans-serif;
      font-weight: 400;
      font-style: normal;
      font-size: 16fpx;
      text-align: left;
    }
  }
  /deep/ .ddiv {
    border-top: 1px solid #dcdfe6;
  }
  /deep/ .dtitle {
    width: 40px;
    text-align: center;
    height: 100%;
    min-height: 100%;
    ul {
      padding: 20px 0 0 0;
    }
  }
  /deep/ .dmain {
    padding: 20px 0 0 0;
    width: calc(100% - 40px);
    border-left: 1px solid #dcdfe6;
  }
}
</style>
