<template>
  <el-form
    v-loading="loading"
    ref="ruleForm"
    :model="ruleForm"
    status-icon
    :rules="rulesThis"
    :label-width="labelWidth || '100px'"
    class="demo-ruleForm"
    :size="size || 'medium'"
  >
    <el-row>
      <el-col :span="24" style="padding: 0 0 20px 0">
        <el-row>
          <el-col :span="20">
            <el-alert
              title="特别关注：手动到对接平台修改商品信息，会被本系统强制覆盖，请谨慎操作！"
              type="error"
              show-icon
              description=""
              :size="'mini'"
              :closable="false"
            >
            </el-alert
          ></el-col>
          <el-col :span="4">
            <el-button
              v-if="!isDetail"
              :size="'mini'"
              type="primary"
              class="fr"
              @click="submitForm()"
              >保 存
            </el-button>
          </el-col>
        </el-row>
      </el-col>

      <el-col :span="6"
        ><el-form-item label="审核状态" prop="exam_status">
          <el-radio-group
            v-model="ruleForm.exam_status"
            placeholder="请选择审核状态"
            style="width: 100%"
            :size="size || 'medium'"
            @change="exam_statusChange"
          >
            <el-radio
              v-for="item in exam_statusList"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="18" v-if="ruleForm.exam_status === '1'">
        <el-row>
          <el-col :span="24">
            <el-form-item label="有赞公用分类" prop="yz_cat_id" label-width="120px">
              <good-class-youzan
                :value="ruleForm.yz_cat_id"
                :placeholder="'请选择分类'"
                @handleChange="handleChange"
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="11">
            <el-form-item label="是否可退货" prop="is_support_barter" label-width="120px">
              <el-radio-group
                v-model="ruleForm.is_support_barter"
                placeholder="请选择是否可退货"
                style="width: 100%"
                :size="'mini'"
              >
                <el-radio
                  v-for="item in is_support_barter_list"
                  :key="item.value"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="24">
            <el-form-item label="允许购买用户标签" prop="tags" label-width="130px">
              <el-select
                v-model="ruleForm.tags"
                multiple
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in tags_options"
                  :key="item.name + item.tag_id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-col>
      <el-col
        :span="24"
        v-show="ruleForm.exam_status === '1'"
        style="padding: 0 0 10px 0"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="商品类型" prop="item_type">
              <el-select
                v-model="ruleForm.item_type"
                placeholder="请选择商品类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in item_type_options"
                  :key="item.label + item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.status === '0'"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="开始出售时间" prop="time" label-width="120px">
              <ul class="item_auto_listing_time clearfix">
                <li class="fl" style="width: 100px">
                  <el-radio
                    v-model="ruleForm.item_auto_listing_time"
                    label="0"
                    @change="item_auto_change"
                    >立即出售</el-radio
                  >
                </li>
                <li class="fl">
                  <el-date-picker
                    v-model="ruleForm.auto_listing_time"
                    type="datetime"
                    style="width: 100%"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择开始出售时间"
                    default-time="12:00:00"
                    @change="time_change"
                    :picker-options="pickerOptions"
                  >
                  </el-date-picker>
                </li>
              </ul>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="划线价" prop="origin">
              <digital-input
                :values="ruleForm.origin"
                :placeholder="'起订量'"
                :min="0"
                :max="100000000000"
                :position="'right'"
                :precision="2"
                :controls="false"
                :append="''"
                :newTime="''"
                :size="''"
                :disabled="false"
                @reschange="num_change($event, 'origin', -1)"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-col>
      <el-col
        :span="24"
        v-show="ruleForm.exam_status === '1'"
        style="padding: 0 0 10px 0"
      >
        <!-- @current-change="handleCurrentChange" -->
        <el-table
          :data="nakelist"
          :size="'mini'"
          border
          stripe
          highlight-current-row
          ref="singleTable"
        >
          <el-table-column label="系统阶梯" width="80px">
            <template slot-scope="scope">
              <i
                v-if="currentRow && currentRow.id === scope.row.id"
                class="el-icon-check"
                style="color: #1890ff; font-size: 16px; font-weight: bolder"
              /> </template
          ></el-table-column>
          <el-table-column prop="min_num" label="采购起订量" />
          <el-table-column label="销售">
            <el-table-column prop="start_sale_num" label="起订量">
              <template slot-scope="scope">
                <!-- <digital-input
                  v-show="scope.row.edit"
                  :values="scope.row.start_sale_num"
                  :placeholder="'起订量'"
                  :min="scope.row.min_num"
                  :max="100000000000"
                  :position="'right'"
                  :precision="0"
                  :controls="false"
                  :append="''"
                  :newTime="scope.row.newTime"
                  :size="'mini'"
                  :disabled="false"
                  @reschange="num_change($event, 'start_sale_num', scope.$index)"
                />
                v-show="!scope.row.edit" -->
                <span>
                  {{ scope.row.start_sale_num }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="sale_good_price" label="系统售价" />
            <el-table-column prop="sale_cost_fee" label="系统工艺费" />
            <el-table-column prop="final_price" label="最终售价">
              <template slot-scope="scope">
                <digital-input
                  v-show="scope.row.edit"
                  :values="scope.row.final_price"
                  :placeholder="'最终售价'"
                  :min="scope.row.sale_good_price"
                  :max="9999999"
                  :position="'right'"
                  :precision="2"
                  :controls="false"
                  :append="''"
                  :newTime="scope.row.newTime"
                  :size="'mini'"
                  :disabled="false"
                  @reschange="num_change($event, 'final_price', scope.$index)"
                />
                <span v-show="!scope.row.edit">
                  {{ scope.row.final_price }}
                </span>
              </template></el-table-column
            >
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="18" v-show="ruleForm.exam_status !== '1'">
        <el-form-item label="审核备注" prop="reject_reason">
          <el-input
            type="textarea"
            placeholder="审核备注"
            v-model="ruleForm.reject_reason"
            :disabled="disabled"
            maxlength="250"
            show-word-limit
            :autosize="{ minRows: 3, maxRows: 3 }"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import asyncRequest from "@/apis/service/youzan/othgoodsOnline";
import { item_type_options } from "../columns";
export default {
  name: "exam-form",
  props: ["size", "statusList", "disabled", "isMust", "labelWidth", "time", "sitem"],
  /**
   * 属性集合
   * @param {String}        size             : 组件大小             非必填
   * @param {Array}         statusList       : 驳回至备选项          必填
   * @param {Boolean}       disabled         : 是否禁用              必填
   * @param {Boolean}       isMust           : 是否需要展示驳回节点   必填
   *
   *
   */
  /**
   * 事件集合
   * @searchChange             : 选中值变化调用   抛出选中数据
   */
  data() {
    const validatetime = (rule, value, callback) => {
      const { item_auto_listing_time, auto_listing_time } = this.ruleForm;
      const type = item_auto_listing_time ?? "";
      const time = auto_listing_time ?? "";
      // console.log(item_auto_listing_time, auto_listing_time);
      if (type === "" && time === "") {
        callback(new Error("请选择开始出售时间！"));
      } else {
        callback();
      }
    };
    const validate_num_0 = (rule, value, callback) => {
      const val = value ?? "";
      const { required } = rule;
      if (required && val === "") {
        callback(new Error("不能为空！"));
      } else if (
        required &&
        (val === "0" ||
          val === "0." ||
          val === "0.0" ||
          val === "0.00" ||
          val === "0.000")
      ) {
        callback(new Error("不能为零！"));
      } else {
        callback();
      }
    };
    return {
      platform_id: "",
      spuCode: "",
      loading: true,
      currentRow: null,
      nakelist: [],
      tags_options: [],
      item_type_options,
      exam_statusList: [
        {
          value: "1",
          label: "通过",
        },
        {
          value: "2",
          label: "驳回",
        },
      ],
      is_support_barter_list: [
        {
          value: "1",
          label: "支持",
        },
        {
          value: "0",
          label: "不支持",
        },
      ],
      showModelThis: this.showModel,
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < new Date().valueOf() - 1000 * 60 * 60 * 24;
        },
      },
      ruleForm: {
        exam_status: "1", // 通过or驳回
        yz_cat_id: [],
        rebut: "", //驳回至
        reject_reason: "",
        tags: [],
        item_type: "0",
        item_auto_listing_time: "0",
        auto_listing_time: "",
        origin: "0",
        time: "0",
      },
      rulesThis: this.rules,
      rules: {
        exam_status: [
          {
            required: true,
            message: "请选择审核状态",
            trigger: "change",
          },
        ],

        is_support_barter: [
          {
            required: false,
            message: "请选择是否可退",
            trigger: "change",
          },
        ],
        tags: [
          {
            required: false,
            type: "array",
            trigger: "change",
          },
        ],
        yz_cat_id: [
          {
            required: true,
            type: "array",
            message: "请选择有赞公用分类",
            trigger: "change",
          },
        ],
        reject_reason: [
          { required: true, message: "请输入审核备注", trigger: "blur" },
          {
            min: 1,
            max: 250,
            message: "长度在 1 到 250 个字符",
            trigger: "blur",
          },
        ],
        origin: [
          {
            required: true,
            validator: validate_num_0,
            trigger: "blur",
          },
        ],
        time: [
          {
            required: true,
            validator: validatetime,
            trigger: "change,blur",
          },
        ],
        item_type: [
          {
            required: true,
            message: "请选择商品类型",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    isDetail: function (val, old) {
      if (this.isDetail !== val) {
        this.options = [];
        this.selectLoading = false;
      }
    },
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      // this.loading = true;
      this.rulesThis = this.rules;
      await this.resetForm();
      this.exam_statusChange();
      await this.get_tags();
      const { nakelist, spuCode, platform_id } = this.sitem;
      this.spuCode = spuCode;
      this.platform_id = platform_id;
      console.log(this.sitem);
      this.nakelist = JSON.parse(JSON.stringify(nakelist));
      this.nakelist.forEach(async (si, sii) => {
        si.start_sale_num = si.min_num;
        let { isok, price, sale_cost_fee } = await this.get_new(sii);
        if (isok === 0) {
          this.nakelist[sii].sale_good_price = price;
          this.nakelist[sii].sale_cost_fee = sale_cost_fee;
          this.nakelist[sii].newTime = new Date().valueOf() + "";
        } else if (isok >= 100 && isok <= 104) {
          await this.logout();
        } else {
          this.nakelist[sii].sale_good_price = price;
          this.nakelist[sii].sale_cost_fee = sale_cost_fee;
          this.nakelist[sii].newTime = new Date().valueOf() + "";
        }
        this.$set(this.nakelist, sii, this.nakelist[sii]);
      });

      // this.setCurrent(this.nakelist[0]);
      let index = this.nakelist.findIndex((e) => e.min_num + "" === "1");
      if (index !== -1) {
        this.handleCurrentChange(this.nakelist[index]);
      }

      this.loading = false;
    },
    item_auto_change() {
      const { item_auto_listing_time } = this.ruleForm;
      if (item_auto_listing_time === "0") {
      }
      this.ruleForm.auto_listing_time =
        item_auto_listing_time === "0" ? "" : this.ruleForm.auto_listing_time;
      this.ruleForm.time =
        this.ruleForm.item_auto_listing_time || this.ruleForm.auto_listing_time;
      this.$refs.ruleForm.validateField("time");
    },
    time_change() {
      const { auto_listing_time } = this.ruleForm;
      this.ruleForm.item_auto_listing_time = auto_listing_time === "" ? "0" : "";
      this.ruleForm.time =
        this.ruleForm.item_auto_listing_time || this.ruleForm.auto_listing_time;
      this.$refs.ruleForm.validateField("time");
    },
    async get_tags() {
      const { code, data, message } = await asyncRequest.tag_list({});
      if (code === 0) {
        this.tags_options = data;
      } else if (code >= 100 && code <= 104) {
        this.tags_options = [];
        await this.logout();
      } else {
        this.tags_options = [];
        this.$message.warning(message);
      }
    },
    exam_statusChange() {
      const { exam_status } = this.ruleForm;
      const isok = exam_status === "1";
      // this.rulesThis.is_support_barter[0].required = isok;
      this.rulesThis.yz_cat_id[0].required = isok;
      this.rulesThis.item_type[0].required = isok;
      this.rulesThis.time[0].required = isok;
      this.rulesThis.origin[0].required = isok;
      this.rulesThis.reject_reason[0].required = !isok;
    },
    num_change(e, key, index) {
      if (index === -1) {
        // console.log(key, e);
        this.ruleForm[key] = e;
        this.$refs.ruleForm.validateField(key);
      } else {
        this.nakelist[index][key] = e;
        this.nakelist[index].newTime = new Date().valueOf() + "";
        // this.$set(this.nakelist, index, this.nakelist[index]);
      }
    },
    handleChange(e) {
      this.ruleForm.yz_cat_id = e;
      this.$refs.ruleForm.validateField("yz_cat_id");
    },
    // setCurrent(row) {
    //   this.$refs.singleTable.setCurrentRow(row);
    // },
    async get_new(index) {
      console.log(index);
      const { min_num } = this.nakelist[index];
      const { code, data, message } = await asyncRequest.goodupprice({
        min_num: min_num,
        platform_id: this.platform_id,
        spuCode: this.spuCode,
      });
      const resModel = {
        isok: code,
        price: code === 0 ? data.sale_price : "0",
        sale_cost_fee: code === 0 ? data.new_cost_fee : "0",
        message: message,
      };
      return resModel;
    },
    handleCurrentChange(val) {
      this.currentRow = val;
      const { id } = val;
      this.nakelist.forEach((si, sii) => {
        this.nakelist[sii].edit = false;
        if (id && id === si.id) {
          this.nakelist[sii].edit = true;
        }
        this.$set(this.nakelist, sii, this.nakelist[sii]);
      });
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            exam_status: "1", // 通过or驳回
            yz_cat_id: [],
            is_support_barter: "1",
            reject_reason: "",
            tags: [],
            item_type: "0",
            item_auto_listing_time: "0",
            auto_listing_time: "",
            origin: "0",
            time: "0",
          };
        }
      });
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) return;
          await this.$confirm(`确定要提交？`, {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              this.loading = true;
              let model = JSON.parse(JSON.stringify(this.ruleForm));
              const {
                yz_cat_id,
                item_auto_listing_time,
                auto_listing_time,
                origin,
              } = this.ruleForm;

              // console.log(yz_cat_id);
              model.platform_youzan_id = this.sitem.platform_youzan_id;
              model.yz_cat_id = "";
              model.good_ladder_id = "";
              model.final_price = "";
              model.start_sale_num = "";
              const { exam_status } = this.ruleForm;
              const isok = exam_status === "1";
              if (isok) {
                const { id } = this.currentRow;
                if (!id) {
                  this.$message.warning("请选择一个系统阶梯！");
                  this.loading = false;
                  return;
                }
                let is_ok = true;
                this.nakelist.forEach((e) => {
                  if (e.sale_good_price + "" === "0" && e.sale_cost_fee + "" === "0") {
                    is_ok = false;
                  }
                });
                if (!is_ok) {
                  this.$message.warning("暂无系统售价，请设置毛利率！");
                  this.loading = false;
                  return;
                }

                let index = this.nakelist.findIndex((si) => si.id === id);
                const {
                  min_num,
                  start_sale_num,
                  sale_good_price,
                  sale_cost_fee,
                  final_price,
                } = this.nakelist[index];
                if (parseInt(start_sale_num) < parseInt(min_num)) {
                  this.$message.warning("销售起订量不小于采购起订量！");
                  this.loading = false;
                  return;
                }
                if (!final_price) {
                  this.$message.warning("最终售价不能为空！");
                  this.loading = false;
                  return;
                }
                if (sale_good_price * 100 > final_price * 100) {
                  this.$message.warning("销售起订量不小于采购起订量！");
                  this.loading = false;
                  return;
                }
                let am = 0;
                const m = auto_listing_time ?? "",
                  nm = new Date().valueOf(),
                  fp = final_price * 100,
                  op = origin * 100;
                if (m !== "0") {
                  am = new Date(auto_listing_time).valueOf();
                }
                if (am !== 0 && nm >= am) {
                  this.$message.warning("开始出售时间不能小于当前时间！");
                  this.loading = false;
                  return;
                }
                if (op < fp) {
                  this.$message.warning("划线价不能小于最终售价！");
                  this.loading = false;
                  return;
                }
                model.platform_youzan_id = this.sitem.platform_youzan_id;
                model.yz_cat_id = yz_cat_id[yz_cat_id.length - 1];
                model.good_ladder_id = id;
                model.final_price = final_price;
                model.start_sale_num = start_sale_num;
                model.auto_listing_time =
                  model.time !== "0" ? new Date(model.time).valueOf() : "0";
                delete model["time"];
                delete model["item_auto_listing_time"];
              }
              const { code, message } = await asyncRequest.goodupexam(model);
              if (code === 0) {
                this.$notify.success({
                  title: "提交成功！",
                  message: "",
                });
                this.$emit("searchChange");
              } else if (code >= 100 && code <= 104) {
                await this.logout();
              } else {
                this.$message.warning(message);
              }
            })
            .catch(() => {
              console.log("取消");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async setstatus(model) {},
  },
};
</script>

<style>
.item_auto_listing_time .fl:last-child {
  width: calc(100% - 115px);
}
</style>
