<template>
  <el-dialog
    :title="title"
    :center="true"
    align="left"
    top="12vh"
    width="900px"
    @close="showModelThis = false"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    v-loading="loading"
    append-to-body
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-card style="margin-top: -20px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            label-position="right"
            label-width="110px"
            :model="ruleForm"
            :rules="rulesThis"
            ref="ruleForm"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="组织/企业：" prop="region">
                  <el-select
                    v-model="ruleForm.region"
                    style="width: 100%"
                    :disabled="isDetail !== '003'"
                    placeholder="请选择组织/企业"
                  >
                    <el-option label="组织" value="0"></el-option>
                    <el-option label="企业" value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上级组织" prop="pid">
                  <el-input
                    v-model="organName"
                    disabled
                    :placeholder="organName ? '上级组织' : '暂无上级组织'"
                    minlength="100"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24" v-if="ruleForm.region === '0'">
                <el-form-item label="组织名称：" prop="name">
                  <el-input
                    v-model="ruleForm.name"
                    :disabled="isDetail == '007'"
                    placeholder="组织名称"
                    minlength="50"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="ruleForm.region === '1'">
                <el-form-item label="企业名称：" prop="companyName">
                  <el-input
                    v-model="ruleForm.companyName"
                    :disabled="isDetail == '007'"
                    placeholder="企业名称"
                    minlength="50"
                    ><template v-if="organName" slot="prepend">{{
                      organName
                    }}</template></el-input
                  >
                </el-form-item>
              </el-col>
              <el-col
                :span="24"
                v-if="ruleForm.region === '1'"
                style="padding: 0 0 16px 0"
              >
                <el-table
                  :data="tableData"
                  :size="'mini'"
                  border
                  style="width: 100%"
                >
                  <el-table-column
                    prop="contactor"
                    label="联系人"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="commobile"
                    label="联系电话"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="position"
                    label="职位"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="comdepart"
                    label="所在部门"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="wxaccount"
                    label="微信号"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="qqaccount"
                    label="qq号"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="email"
                    label="邮箱"
                    show-overflow-tooltip
                  />
                  <el-table-column fixed="right" v-if="isDetail !== '007'">
                    <template slot="header" slot-scope="scope">
                      <span>操作</span>
                      <el-tooltip
                        class="item"
                        effect="dark"
                        content="添加"
                        placement="top"
                      >
                        <i
                          class="el-icon-circle-plus-outline fr"
                          style="font-size: 18px; margin-top: 2px"
                          @click="openEdit('-1', {})"
                        />
                      </el-tooltip>
                    </template>
                    <template slot-scope="scope">
                      <el-tooltip effect="dark" content="修改" placement="top">
                        <i
                          class="el-icon-edit tb-icon"
                          @click="openEdit(scope.$index, scope.row)"
                        ></i>
                      </el-tooltip>
                      <el-tooltip
                        effect="dark"
                        content="禁/启用"
                        placement="top"
                      >
                        <i
                          class="el-icon-delete tb-icon"
                          @click="openDelete(scope.$index)"
                        ></i>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
                <contact-modal
                  :showModel="editModel"
                  :index="findex"
                  :sitem="sitem"
                  @cancel="editModel = false"
                  @refresh="contactRefresh"
                />
              </el-col>
              <el-col :span="24" style="text-align: right">
                <el-button
                  v-if="isDetail !== '007'"
                  type="primary"
                  @click="submitForm"
                  >保 存
                </el-button>
                <el-button @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/serviceParam/business";
import contactModal from "./contactModal";
export default {
  name: "goodsBack",
  props: ["showModel", "isDetail", "id", "organ", "kh"],
  mixins: [resToken],
  components: {
    contactModal,
  },
  data() {
    return {
      findex: -1,
      sitem: null,
      editModel: false,
      loading: false,
      title: "添加企业/组织",
      showModelThis: this.showModel,
      ruleForm: {},
      rulesThis: this.rules,
      organName: "",
      tableData: [],
      old_tableData: [],
      rules: {
        region: [
          {
            required: true,
            message: "请选择组织/企业",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "组织名称不能为空",
            trigger: "blur",
          },
        ],
        companyName: [
          {
            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.tableData = [];
      this.old_tableData = [];
      this.organName = "";
      await this.resetForm();
      if (this.isDetail === "003") {
        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();
      }
      this.setOrganName();
      this.loading = false;
    },
    setOrganName() {
      this.organName = "";
      if (this.organ && this.organ.length > 1) {
        this.organ.forEach((e) => {
          if (e.id !== "0") {
            console.log(e.name);
            this.organName += e.name;
            this.ruleForm.pid = e.id;
          }
        });
      } else {
        this.organName = "";
      }
      const { companyName } = this.ruleForm;
      let isok = companyName.indexOf(this.organName) == 0;
      if (isok) {
        let str = companyName;
        this.ruleForm.companyName = str.substring(
          this.organName.length,
          this.ruleForm.companyName.length
        );
      }
      console.log(isok);
    },
    openEdit(index, sitem) {
      this.findex = index;
      this.sitem = sitem;
      this.editModel = true;
    },
    openDelete(index) {
      this.tableData.splice(index, 1);
    },
    async resetForm() {
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            id: "",
            pid: "0",
            region: "0",
            name: "",
            companyName: "",
          };
        }
      });
    },
    async initData() {
      let res = {};
      if (this.kh + "" === "0") {
        res = await asyncRequest.zdetail({ id: this.id });
      } else {
        res = await asyncRequest.qdetail({ id: this.id });
      }
      const { code, data, message } = res;
      if (code === 0) {
        const { pid, name, pname, companyName, parent, member } = data;
        console.log(data);
        this.organName = pname;
        this.ruleForm = {
          id: this.id,
          region: this.kh + "" || "0",
          pid: parent ? parent : pid ? pid : "0",
          name: name || "",
          companyName: companyName || "",
        };
        if (member && member.length > 0) {
          this.old_tableData = JSON.parse(JSON.stringify(member));
          this.tableData = JSON.parse(JSON.stringify(member));
        } else {
          this.old_tableData = [];
          this.tableData = [];
        }
        this.$refs.ruleForm.resetFields();
        this.$refs.ruleForm.clearValidate();
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
    contactRefresh(e) {
      this.editModel = false;
      const {
        index,
        contactor,
        commobile,
        position,
        comdepart,
        wxaccount,
        qqaccount,
        email,
        id,
        is_del,
      } = e;
      if (index + "" === "-1") {
        this.tableData.push(e);
      } else {
        let findex = parseInt(index);
        this.tableData[findex].contactor = contactor || "";
        this.tableData[findex].commobile = commobile || "";
        this.tableData[findex].position = position || "";
        this.tableData[findex].comdepart = comdepart || "";
        this.tableData[findex].wxaccount = wxaccount || "";
        this.tableData[findex].qqaccount = qqaccount || "";
        this.tableData[findex].email = email || "";
        this.tableData[findex].id = id || "";
        this.tableData[findex].is_del = is_del || "0";
      }
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const { id, pid, name, companyName } = this.ruleForm;
          let res = {};
          if (this.ruleForm.region === "0") {
            let zitem = {
              id: id,
              pid: pid,
              name: name,
            };
            if (this.isDetail === "003") {
              delete zitem["id"];
              res = await asyncRequest.zadd(zitem);
            } else {
              res = await asyncRequest.zupdate(zitem);
            }
          } else {
            if (this.tableData.length === 0) {
              this.$message.warning("至少填写一个联系人！");
              this.loading = false;
              return;
            }
            let qitem = {
              id: id,
              companyName: this.organName + companyName,
              parent: pid,
              customer_member: this.getCustomer(),
            };

            if (this.isDetail === "003") {
              delete qitem["id"];
              res = await asyncRequest.qadd(qitem);
            } else {
              res = await asyncRequest.qupdate(qitem);
            }
          }
          this.loading = false;
          if (res && res.code === 0) {
            const title = this.isDetail === "003" ? "添加成功!" : "修改成功!";
            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;
        }
      });
    },
    getCustomer() {
      let list = JSON.parse(JSON.stringify(this.tableData));
      let oldlist = JSON.parse(JSON.stringify(this.old_tableData));
      let hasIDlist = [];
      list.forEach((a) => {
        if (a.id !== "") {
          hasIDlist.push(a);
        }
      });
      let newList = [];
      let resList = [];
      oldlist.forEach((a, ai) => {
        let item = null;
        let index = hasIDlist.findIndex((b) => a.id === b.id);
        if (index === -1) {
          item = JSON.parse(JSON.stringify(a));
          item.is_del = "1";
        } else {
          item = JSON.parse(JSON.stringify(hasIDlist[index]));
        }
        newList.push(item);
      });
      list.forEach((b) => {
        if (b.id === "") {
          b.is_del = "0";
          newList.push(b);
        }
      });
      newList.forEach((a) => {
        let m = {
          id: a.id,
          contactor: a.contactor,
          position: a.position,
          commobile: a.commobile,
          comdepart: a.comdepart,
          wxaccount: a.wxaccount,
          qqaccount: a.qqaccount,
          email: a.email,
          is_del: a.is_del || "0",
          status: a.status || "1",
        };
        resList.push(m);
      });

      return resList;
    },
  },
};
</script>

   <style lang="scss" scoped>
.storeAnomaly {
  // width: calc( 100% - 110px);
}
</style>
   