<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="12vh"
    width="600px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    append-to-body
    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-top: -20px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            label-position="right"
            label-width="110px"
            :model="ruleForm"
            :rules="rulesThis"
            size="mini"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item label="上级组织">
                  <el-input
                    v-model="organName"
                    disabled
                    :placeholder="organName ? '上级组织' : '暂无上级组织'"
                    maxlength="100"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="组织/企业：" prop="region">
                  <el-select
                    v-model="ruleForm.region"
                    style="width: 100%"
                    :disabled="isDetail !== '002'"
                    placeholder="组织/企业"
                  >
                    <el-option label="组织" value="0" />
                    <el-option label="企业" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col v-if="ruleForm.region === '0'" :span="24">
                <el-form-item label="组织名称：" prop="name">
                  <el-input
                    style="width: 100%"
                    v-model="ruleForm.name"
                    :disabled="isDetail === '001'"
                    placeholder="组织名称"
                    maxlength="50"
                  />
                </el-form-item>
              </el-col>
              <el-col v-if="ruleForm.region === '1'" :span="24">
                <el-form-item label="企业名称：" prop="companyName">
                  <el-input
                    v-model="ruleForm.companyName"
                    :disabled="isDetail === '001'"
                    placeholder="企业名称"
                    maxlength="50"
                    ><template
                      v-if="organName && ruleForm.region == '1'"
                      slot="prepend"
                      >{{ organName }}</template
                    ></el-input
                  >
                </el-form-item>
              </el-col>

              <el-col :span="24" style="text-align: right">
                <el-button
                  v-if="isDetail !== '007'"
                  size="mini"
                  type="primary"
                  @click="submitForm"
                  >保 存
                </el-button>
                <el-button size="mini" @click="showModelThis = false">{{
                  isDetail == "007" ? "关 闭" : "取 消"
                }}</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/operate/organize";
export default {
  name: "GoodsBack",
  mixins: [resToken],
  props: ["showModel", "isDetail", "id", "organ", "kh", "sitem"],
  data() {
    const validator = function (rule, value, callback) {
      const isValueValid = Array.isArray(value) && value.length > 0;
      if (!isValueValid && this.area !== "0") {
        callback(new Error("企业所在区域不能为空"));
      } else {
        callback();
      }
    };

    return {
      sitem: null,
      loading: false,
      title: "添加企业/组织",
      showModelThis: this.showModel,
      ruleForm: {},
      rulesThis: this.rules,
      organName: "",
      pid: "0",
      rules: {
        region: [
          {
            required: true,
            message: "请选择组织/企业",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "组织名称不能为空",
            trigger: "blur",
          },
        ],
        companyName: [
          {
            required: true,
            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.organName = "";
      this.pid = "0";
      this.setOrganName();
      await this.resetForm();
      if (this.isDetail === "002") {
        this.title = "添加企业/组织";
        this.rulesThis = this.rules;
      } else if (this.isDetail === "005") {
        this.title = "修改企业/组织";
        this.rulesThis = this.rules;
        await this.initData();
      } else {
        this.title = "查看企业/组织";
        this.rulesThis = {};
        await this.initData();
      }

      console.log(this.ruleForm);
      this.loading = false;
    },
    setOrganName() {
      this.organName = "";
      if (this.organ && this.organ.length > 1) {
        this.organ.forEach((e) => {
          if (e.id !== "0") {
            this.organName += e.name;
            this.pid = e.id;
          }
        });
      } else {
        this.organName = "";
        this.pid = "0";
      }
    },

    async resetForm() {
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            id: "",
            pid: this.pid||"0",
            region: "0",
            name: "",
          };
        }
      });
    },
    async initData() {
      const { id, name, kh } = this.sitem;

      this.ruleForm = {
        pid: this.pid,
        id: id || "",
        name: kh + "" === "0" ? name : "",
        region: kh + "" || "0",
        companyName: kh + "" === "1" ? name.replace(this.organName, "") : "",
      };
      console.log(this.sitem);
      console.log(this.ruleForm);
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          const { id, pid, name } = this.ruleForm;
          let res = {};
          if (this.ruleForm.region === "0") {
            const zitem = {
              id: id,
              pid: pid,
              name: name,
            };
            if (this.isDetail === "002") {
              delete zitem["id"];
              res = await asyncRequest.zadd(zitem);
            } else {
              res = await asyncRequest.zupdate(zitem);
            }
          } else {
            const qitem = {
              id: id,
              itemid: pid,
              companyName: this.organName + this.ruleForm.companyName,
            };
            if (this.isDetail === "002") {
              delete qitem["id"];
              res = await asyncRequest.qadd(qitem);
            } else {
              res = await asyncRequest.qupdate(qitem);
            }
          }
          this.loading = false;
          const { code } = res;
          if (code === 1) {
            const title = this.isDetail === "002" ? "添加成功!" : "修改成功!";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            this.$emit("refresh");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

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