<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="12vh"
    width="650px"
    :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">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :rules="rulesThis"
            label-width="95px"
            class="demo-ruleForm"
          >
            <el-form-item label="分类名称" prop="cat_name">
              <el-input
                v-model="ruleForm.cat_name"
                :disabled="id == '007'"
                placeholder="分类名称"
                maxlength="20"
              >
                <template slot="prepend" v-if="pid_name">{{
                  pid_name
                }}</template></el-input
              >
            </el-form-item>
            <el-form-item label="分类规格" prop="specs_id">
              <el-select
                v-model="ruleForm.specs_id"
                multiple
                :disabled="id == '007'"
                style="width: 100%"
                placeholder="分类规格"
              >
                <el-option
                  v-for="item in specOptions"
                  :key="item.id"
                  :label="item.spec_name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="财务核算码" prop="fund_code">
              <el-input
                v-model="ruleForm.fund_code"
                :disabled="id == '007'"
                placeholder="财务核算码"
                maxlength="50"
              />
            </el-form-item> -->
            <el-form-item label="售后说明" prop="cat_desc">
              <el-input
                v-model="ruleForm.cat_desc"
                :disabled="id == '007'"
                placeholder="售后说明"
                type="textarea"
                :rows="5"
                maxlength="2000"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button v-if="id !== '007'" type="primary" @click="submitForm"
            >保 存
          </el-button>
          <el-button @click="showModelThis = false">{{
            id == "007" ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/goodStore/sort";
import resToken from "@/mixins/resToken";
import { isChinese } from "@/utils/validate";
export default {
  name: "sort",
  props: ["showModel", "id", "sitem", "titleList"],
  mixins: [resToken],
  data() {
    const validate_fund_code = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else if (isChinese(value)) {
        callback(new Error("财务核算码不能包含汉字！"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      title: "添加分类",
      pid_name: "",
      showModelThis: this.showModel,
      specOptions: [],
      ruleForm: {
        id: "",
        cat_name: "",
        specs_id: [],
        cat_desc: "",
      },
      rulesThis: this.rules,
      rules: {
        cat_name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
        ],
        specs_id: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个分类规格",
            trigger: "change",
          },
        ],
        fund_code: [
          { required: false, validator: validate_fund_code, trigger: "blur" },
        ],

        cat_desc: [{ required: false, message: "", trigger: "blur" }],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.pid_name = "";
      this.titleList.forEach((e, i) => {
        this.pid_name += i !== 0 ? `${e.titleName}/` : "";
      });
      await this.resetForm();
      if (this.id === "003") {
        this.title = "添加分类";
        this.rulesThis = this.rules;
      } else if (this.id === "005") {
        this.title = "修改分类";
        this.rulesThis = this.rules;
        await this.initData();
      } else {
        this.title = "分类详情";
        this.rulesThis = {};
        await this.initData();
      }

      await this.getAllSpecs();

      this.loading = false;
    },

    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const { id, cat_name, cat_desc } = this.sitem;
          this.ruleForm = {
            pid: this.titleList[this.titleList.length - 1].id || "",
            id: id || "",
            cat_name: cat_name || "",
            specs_id: [],
            cat_desc: cat_desc || "",
          };
        }
      });
    },
    async getAllSpecs() {
      this.specOptions = [];
      let res = await asyncRequest.specstitle({});
      if (res && res.code === 0) {
        this.specOptions = res.data;
      } else if (res && res.code >= 100 && res.code <= 104) {
        this.specOptions = [];
        await this.logout();
      } else {
        this.specOptions = [];
        this.$message.warning(res.message);
      }
    },
    async initData() {
      const res = await asyncRequest.detail({ id: this.sitem.id });
      if (res && res.code === 0 && res.data) {
        const { pid, id, cat_name, cat_desc, spec, fund_code } = res.data;
        let specs_id = [];
        if (spec && spec.length > 0) {
          spec.forEach((e) => {
            specs_id.push(e.id);
          });
        }
        console.log(specs_id);
        this.ruleForm = {
          pid: pid || "",
          id: id || "",
          cat_name: cat_name || "",
          specs_id: specs_id || [],
          fund_code: fund_code || "",
          cat_desc: cat_desc || "",
        };
        this.$refs.ruleForm.resetFields();
        this.$refs.ruleForm.clearValidate();
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (!this.loading) {
            this.loading = true;
            let model = JSON.parse(JSON.stringify(this.ruleForm));
            let res = {};
            if (this.id === "003") {
              delete model["id"];
              res = await asyncRequest.add(model);
            } else {
              res = await asyncRequest.update(model);
            }
            this.loading = false;
            if (res && res.code === 0) {
              const title = this.id === "add" ? "添加成功!" : "修改成功!";
              this.$notify.success({
                title,
                message: "",
              });
              this.showModelThis = false;
              // 刷新
              this.$emit("refresh");
            } else if (res && res.code >= 100 && res.code <= 104) {
              await this.logout();
            } else {
              this.$message.warning(res.message);
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

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