<template>
  <el-dialog
    :title="title"
    :center="true"
    align="left"
    top="18vh"
    width="900px"
    @close="closeModel"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-card>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            v-if="isApproval"
            :model="cexForm"
            status-icon
            :rules="cexRules"
            ref="cexForm"
            label-width="80px"
            class="cexForm-ruleForm"
            ><el-row>
              <el-col :span="12">
                <el-row class="cexForm-div" v-if="dataInfo && dataInfo.parent">
                  <el-col :span="8" class="tr cexForm-label">上级分类：</el-col>
                  <el-col :span="16" class="cexForm-main">{{
                    dataInfo.parent.cat_pid === "0"
                      ? dataInfo.parent.cat_name
                      : dataInfo.parent.cat_pid_name +
                        "/" +
                        dataInfo.parent.cat_name
                  }}</el-col>
                </el-row>
                <el-row class="cexForm-div">
                  <el-col :span="8" class="tr cexForm-label">分类名称：</el-col>
                  <el-col :span="16" class="cexForm-main">{{
                    dataInfo.cat_name
                  }}</el-col>
                </el-row>
                <el-row class="cexForm-div">
                  <el-col :span="8" class="tr cexForm-label">规格：</el-col>
                  <el-col :span="16" class="cexForm-main">{{
                    dataInfo.specName
                  }}</el-col>
                </el-row>
                <el-row class="cexForm-div">
                  <el-col :span="8" class="tr cexForm-label">分类备注：</el-col>
                  <el-col :span="16" class="cexForm-main">{{
                    ruleForm.cat_remark
                  }}</el-col>
                </el-row>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审核状态" prop="status">
                  <el-select
                    v-model="cexForm.status"
                    placeholder="请选择审核状态"
                    @change="selectChange"
                  >
                    <el-option
                      v-for="item in statusList"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="审核说明" prop="remark">
                  <el-input
                    v-model="cexForm.remark"
                    type="textarea"
                    placeholder="请输入审核说明"
                    :rows="5"
                    maxlength="300"
                    show-word-limit
                  ></el-input>
                </el-form-item>
                <el-col :span="24" style="text-align: right">
                  <el-button type="primary" @click="submitCexForm"
                    >保 存
                  </el-button>
                  <el-button @click="showModelThis = false">取 消</el-button>
                </el-col>
              </el-col>
            </el-row></el-form
          >

          <el-form
            v-else
            :model="ruleForm"
            status-icon
            :rules="rulesThis"
            ref="ruleForm"
            label-width="80px"
            class="demo-ruleForm"
            ><el-row>
              <el-form-item label="上级分类" prop="pid">
                <el-cascader
                  v-model="ruleForm.pid"
                  style="width: 60%"
                  filterable
                  clearable
                  :options="catOptions"
                  :props="{ expandTrigger: 'hover', checkStrictly: true }"
                  @change="handleChange"
                ></el-cascader>
                <el-tag style="margin: 0 0 0 10px" type="warning"
                  >提示：不选择上级分类时，默认为一级分类</el-tag
                >
              </el-form-item>
              <el-form-item label="分类名称" prop="cat_name">
                <el-input
                  v-model="ruleForm.cat_name"
                  :disabled="isDetail"
                ></el-input>
              </el-form-item>

              <el-form-item label="规格" prop="spec">
                <el-select
                  v-model="ruleForm.spec"
                  multiple
                  filterable
                  style="width: 100%"
                  clearable
                  :disabled="isDetail"
                  class="setWidth"
                >
                  <el-option
                    v-for="item in specOptions"
                    :key="`cat` + item.id"
                    :label="item.spec_name"
                    :value="item.id"
                    :disabled="item.status !== '1'"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备注" prop="cat_remark">
                <el-input
                  v-model="ruleForm.cat_remark"
                  type="textarea"
                  placeholder="请输入备注"
                  :rows="5"
                  maxlength="300"
                  show-word-limit
                  :disabled="isDetail"
                />
              </el-form-item>

              <el-col :span="24" style="text-align: right">
                <el-tag
                  type="warning"
                  class="fl"
                  style="max-width: 500px"
                  v-if="dataInfo.ex_remark && dataInfo.ex_status === '2'"
                  >审核备注：{{ dataInfo.ex_remark }}</el-tag
                >

                <el-button type="primary" @click="submitForm" v-if="!isDetail"
                  >保 存
                </el-button>
                <el-button @click="showModelThis = false">{{
                  isDetail ? "关 闭" : "取 消"
                }}</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
   <script>
import asyncRequest from "@/apis/service/goodStore/sort";
import {
  isnumber,
  isMobile,
  validEmail,
  isAlphanumeric,
  isChinese,
  isEmoticon,
  validAlphabets,
} from "@/utils/validate";
import statusList from "@/assets/js/cexStatusList";
export default {
  name: "specs",
  props: ["showModel", "id", "isDetail", "isApproval"],
  data() {
    const validatename = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("分类名称不能为空！"));
      } else {
        callback();
        // if (value.lenght < 2 || value.lenght > 12) {
        //   callback(new Error("分类名称规则为2~12位汉字！"));
        // } else {
        //   if (!isChinese(value)) {
        //     console.log(9999);
        //     callback(new Error("分类名称规则为2~12位汉字！"));
        //   } else if (isEmoticon(value)) {
        //     console.log(2345);
        //     callback(new Error("分类名称规则为2~12位汉字！"));
        //   } else {
        //     callback();
        //   }
        // }
      }
    };
    return {
      statusList: statusList,
      specOptions: [],
      catOptions: [],
      loading: false,
      title: "商品分类",
      showModelThis: this.showModel,
      dataInfo: {},
      cexForm: {
        catid: this.id,
        remark: "",
        status: "1",
      },
      ruleForm: {
        catid: this.id,
        spec: "",
        cat_name: "",
        spec: [],
        cat_remark: "",
      },
      cexRules: {
        status: {
          required: true,
          message: "请选择审核状态",
          trigger: "change",
        },
        remark: [
          {
            required: false,
            message: "请输入审核说明！",
            trigger: "blur",
          },
        ],
      },
      rulesThis: this.rules,
      rules: {
        pid: [
          {
            required: false,
            message: "请选择上级分类",
            trigger: "change",
          },
        ],
        cat_name: [
          {
            required: true,
            validator: validatename,
            trigger: "blur",
          },
        ],
        spec: [
          {
            required: true,
            message: "请选择规格",
            trigger: "change",
          },
        ],

        cat_remark: [
          {
            required: false,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    closeModel() {
      console.log("closeModel!!");
    },
    selectChange() {
      if (this.cexForm.status === "1") {
        this.cexRules.remark[0].required = false;
      } else {
        this.cexRules.remark[0].required = true;
      }
    },
    async initForm() {
      this.loading = true;
      await this.getAllCat();
      await this.getAllSpec();
      if (this.isApproval) {
        this.title = "商品分类审核";
        await this.initData();
        await this.resetcexForm();
        this.selectChange()
      } else {
        if (this.id === "add") {
          this.title = "添加商品分类";
          // this.ruleForm.isAdmin = 0;
          this.loading = false;
          this.rulesThis = this.rules;
          await this.resetForm();
        } else {
          if (this.isDetail) {
            this.title = "商品分类详情";
            this.rulesThis = {};
          } else {
            this.title = "修改商品分类";
            this.rulesThis = this.rules;
          }
          await this.initData();
        }
        this.loading = false;
      }
    },
    async initData() {
      this.loading = true;
      let res = await asyncRequest.detail({ catid: this.id });
      this.loading = false;
      if (res.code === 0) {
        let data = res.data;
        this.dataInfo = data;
        let list = this.dataInfo.spec;
        let str = "";
        this.specOptions.forEach((v1) => {
          let find = list.findIndex((v2) => v2 === v1.id);
          if (find !== -1) {
            str +=
              str === ""
                ? this.specOptions[find].spec_name
                : "," + this.specOptions[find].spec_name;
          }
        });
        this.dataInfo.specName = str;
        if (this.dataInfo.parent && this.dataInfo.parent.cat_pid !== "0") {
          let pid = this.dataInfo.parent.cat_pid;
          let index = -1;
          index = this.catOptions.findIndex((v1) => v1.id === pid);
          if (index !== -1) {
            this.dataInfo.parent.cat_pid_name = this.catOptions[index].cat_name;
          } else {
            this.dataInfo.parent.cat_pid_name = "";
          }
        }
        await this.resetForm(data);
      }
    },
    async getAllCat() {
      const res = await asyncRequest.catAll({});
      if (res.code === 0 && res.data) {
        let list = res.data;
        list.map((v1) => {
          v1.value = v1.id;
          v1.label = v1.cat_name;
          if (v1.child && v1.child.length > 0) {
            v1.child.map((v2) => {
              v2.value = v2.id;
              v2.label = v2.cat_name;
              v2.child = [];
              // v2.children = v2.child;
              return v2;
            });
          }
          v1.children = v1.child;
          return v1;
        });
        this.catOptions = list;
      }
    },
    async getAllSpec() {
      const res = await asyncRequest.specAll({});
      if (res.code === 0 && res.data) {
        this.specOptions = res.data;
      }
    },
    async resetForm(data) {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          if (data) {
            this.ruleForm.catid = this.id;
            this.ruleForm.cat_remark = data.cat_dec;
            this.ruleForm.cat_name = data.cat_name;
            this.ruleForm.pid = [];
            if (data.parent) {
              if (data.parent.cat_pid !== "0") {
                this.ruleForm.pid.push(data.parent.cat_pid);
              }
              if (data.parent.id) {
                this.ruleForm.pid.push(data.parent.id);
              }
            } else {
              this.ruleForm.pid = [];
            }
            // data.spec
            this.ruleForm.spec = data.spec;
            console.log(this.ruleForm);
          } else {
            this.ruleForm = {
              catid: this.id,
              spec: [],
              cat_name: "",
              pid: [],
              cat_remark: "",
            };
          }
        }
      });
    },
    async resetcexForm() {
      if (this.$refs.cexForm) {
        this.$refs.cexForm.resetFields();
        this.$refs.cexForm.clearValidate();
        this.cexForm = {
          catid: this.id,
          remark: "",
          status: "1",
        };
      }
    },
    async submitCexForm() {
      await this.$refs.cexForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          console.log(this.id);
          console.log(this.cexForm);
          let obj = JSON.parse(JSON.stringify(this.cexForm));
          obj.id = this.id;
          console.log(obj);
          let res = await asyncRequest.exam(obj);
          this.loading = false;
          if (res.code === 0) {
            let title = "审核审批成功！";
            this.$notify.success({
              title,
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refresh");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async submitForm() {
      console.log(12345);
      await this.$refs.ruleForm.validate( async (valid) => {
        console.log(valid);
        if (valid) {
          this.loading = true;
          let obj = JSON.parse(JSON.stringify(this.ruleForm));
          obj.pid = obj.pid.join();
          obj.spec = obj.spec.join();
          if (obj.pid === "") {
            obj.pid = "0";
          }

          let res = {};
          if (this.id === "add") {
            delete obj["catid"];
            res = await asyncRequest.add(obj);
          } else {
            res = await asyncRequest.update(obj);
          }
          this.loading = false;
          if (res.code === 0) {
            let title = this.id === "add" ? "添加成功" : "修改成功";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refresh");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  watch: {
    showModel: function (val) {
      console.log(val);
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
};
</script>

   <style lang="scss" scoped>
.sort {
  .cexForm-ruleForm {
    .cexForm-div {
      margin-bottom: 2px;
      .cexForm-label {
        padding-right: 12px;
        color: #606266;
        line-height: 40px;
        font-size: 14px;
      }
      .cexForm-main {
        line-height: 40px;
        color: rgb(151, 168, 190);
        line-height: 40px;
        font-size: 14px;
      }
    }
  }
}
</style>