<template>
  <div style="display: flex">
    <div :style="'margin-left: 5px;width:' + (window.pageWidth - 200 - 120 - 45) + 'px;'">
      <!--overflow-y: scroll;height:200px;-->
      <el-form ref="form" :model="form" label-width="85px" :rules="rules" size="medium">
        <el-row>
          <el-col :span="8">
            <el-form-item label="上级单位" prop="parentId">
              <el-cascader v-model="form.parentId" :options="customerOrg.customerOrgTree"
                :props="{checkStrictly: true,expandTrigger: 'hover',...customerOrg.treeprops,}"
                :show-all-levels="false" clearable filterable disabled
                :style="'width:' + Math.floor((window.pageWidth - 620) / 3) + 'px;'">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位名称" prop="displayName">
              <el-input class="enterToTab" v-model="form.displayName" placeholder="请输入单位名称" :disabled="customerOrg.oprStatus ? false:true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位简称" prop="shortName">
              <el-input class="enterToTab" v-model="form.shortName" placeholder="请输入单位简称" :disabled="customerOrg.oprStatus ? false:true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="体检中心" prop="organizationUnitId">
              <el-select
                v-model="form.organizationUnitId"
                placeholder="请选择"
                filterable
                :disabled="peisid ? true : false"
                :style="'width:' + Math.floor((window.pageWidth - 620) / 3) + 'px;'"
              >
                <el-option
                  v-for="item in data.organizationdata"
                  :key="item.id"
                  :label="item.displayName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位性质" prop="orgTypeId">
              <el-select class="enterToTab" 
                v-model="form.orgTypeId"
                placeholder="请选择"
                filterable
                :style="'width:' + Math.floor((window.pageWidth - 620) / 3) + 'px;'"
              >
                <el-option
                  v-for="item in data.customerOrgType"
                  :key="item.id"
                  :label="item.displayName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!--
            <el-form-item label="显示顺序" prop="displayOrder">
              <el-input type="number" v-model="form.displayOrder" />
            </el-form-item>
            -->

          <!--
            <el-form-item label="单位简码" prop="simpleCode">
              <el-input v-model="form.simpleCode" placeholder="由系统自动生成" disabled />
            </el-form-item>
            -->

          <el-col :span="8">
            <el-form-item label="联系电话" prop="telephone">
              <el-input class="enterToTab"  v-model="form.telephone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="传真" prop="fax">
              <el-input class="enterToTab" v-model="form.fax" placeholder="请输入传真" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮政编码" prop="postalCode">
              <el-input class="enterToTab" v-model="form.postalCode" placeholder="请输入邮政编码" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="加锁" prop="isLock" label-width="56px">
              <!--
              <el-radio v-model="form.isLock" label="Y" >是</el-radio>
              <el-radio v-model="form.isLock" label="N" >否</el-radio>
              -->
              <el-checkbox v-model="form.isLockBox" @change="changeBox" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="启用" prop="isActive" label-width="56px">
              <!--
              <el-radio v-model="form.isActive" label="Y">启用</el-radio>
              <el-radio v-model="form.isActive" label="N">停用</el-radio>              
              -->
              <el-checkbox v-model="form.isActiveBox" @change="changeBox('isActive')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发票抬头" prop="invoiceName">
              <el-input class="enterToTab" v-model="form.invoiceName" placeholder="请输入发票抬头" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开户银行" prop="bank">
              <el-input class="enterToTab" v-model="form.bank" placeholder="请输入开户银行" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="银行账号" prop="accounts">
              <el-input class="enterToTab" v-model="form.accounts" placeholder="请输入银行账号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input class="enterToTab" 
                v-model="form.address"
                placeholder="请输入地址"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input class="enterToTab" v-model="form.remark" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="创建人员">
              <el-input v-model="form.creatorName" size="small" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="form.creationTime"
                type="datetime"
                size="small"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="修改人员">
              <el-input v-model="form.lastModifierName" size="small" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="修改时间">
              <el-date-picker
                v-model="form.lastModificationTime"
                type="datetime"
                size="small"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 按钮区域 -->
    <div style="width: 110px; margin-left: 10px; margin-top: 3%">
      <div v-show="checkPagePriv(pagePriv.privs,'新增单位')" class="btnList">
        <el-button type="primary" @click="add('form', '')" class="commonbutton"
          >新增单位</el-button
        >
      </div>
      <div v-show="checkPagePriv(pagePriv.privs,'新增子单位')" class="btnList">
        <el-button type="primary" @click="add('form', 'child')" class="commonbutton"
          >新增子单位</el-button
        >
      </div>
      <div v-show="checkPagePriv(pagePriv.privs,'保存')" class="btnList">
        <el-button type="success" @click="btnSubmit('form')" class="commonbutton"
          ><i class="el-icon-check"></i>保存</el-button
        >
      </div>
      <div v-show="checkPagePriv(pagePriv.privs,'删除')" class="btnList">
        <el-button type="danger" @click="del('form')" class="commonbutton">
          <i class="el-icon-delete"></i>删除
        </el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { getPagePriv,checkPagePriv,tcdate, objCopy, deepCopy, arrayExistObj } from "../../utlis/proFunc";
import { getTreeNode, getTreePids } from "../../utlis/tree";

export default {
  components: {},
  props: ["id"],
  data() {
    return {
      pagePriv:{
        routeUrlorPageName:'customerOrg', //当前页面归属路由或归属页面权限名称
        privs:[] // 页面权限
      }, 
      isActiveBox: false,
      customerOrgEditStyle: "height:400px;",
      data: {
        organizationdata: [], //体检中心数据
        customerOrgType: [], //单位类别
      },
      peisid: null,

      form: {
        id: "",
        displayName: "",
        shortName: "",
        invoiceName: "",
        parentId: null,
        telephone: "",
        fax: "",
        postalCode: "",
        address: "",
        bank: "",
        accounts: "",
        orgTypeId: null,
        remark: "",
        isLock: "N",
        isActive: "Y",
        isLockBox: false,
        isActiveBox: true,
        organizationUnitId: null,
        creatorName: "",
        creationTime: null,
        lastModifierName: "",
        lastModificationTime: null,
      }, //初始化  单位 记录 目前新增与更新是一致

      rules: {
        displayName: [{ required: true, message: "请输入单位名称", trigger: "blur" }],
        shortName: [{ required: true, message: "请输入单位简写", trigger: "blur" }],
        organizationUnitId: [
          { required: true, message: "请输入体检中心", trigger: "blur" },
        ],
      },

      isshow: false,
    };
  },

  created() {   
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem('userPriv')
    if(userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))
    
    this.peisid = window.sessionStorage.getItem("peisid");
    if (!this.form.id) {
      this.form.organizationUnitId = this.peisid;
    }
  },

  //挂载完成
  mounted() {
    // 表单中 回车 代替 tab
    this.enterToTab();

    //获取体中心字典数据
    this.getoraniztion();

    //获取单位类别列表
    this.getOrgType();

    this.getCustomerOrgRd(this.id);


  },

  computed: {
    ...mapState(["customerOrg", "window"]),
  },
  methods: {
    ...mapMutations(["setData"]),checkPagePriv,

    changeBox(type) {
      //赋值
      if (this.form[type + "Box"]) {
        this.form[type] = "Y";
      } else {
        this.form[type] = "N";
      }
    },

    //获取单位信息
    getCustomerOrgRd(id) {
      if (!id) return;
      getapi(`/api/app/customer-org/${id}`).then((res) => {
        if (res.code != -1) {
          objCopy(res.data, this.form);

          if (res.data.isActive == "Y") {
            this.form.isActiveBox = true;
          } else {
            this.form.isActiveBox = false;
          }
          if (res.data.isLock == "Y") {
            this.form.isLockBox = true;
          } else {
            this.form.isLockBox = false;
          }
        }
      });
    },

    //获取组织体检中心数据
    getoraniztion() {
      getapi("/api/app/organization-units/organization-unit-by-is-peis").then((res) => {
        this.data.organizationdata = res.data;
      });
    },

    //获取单位类别列表
    getOrgType() {
      getapi("/api/app/customer-org-type/in-filter").then((res) => {
        this.data.customerOrgType = res.data.items;
      });
    },

    //更新获取单位树节点数据(局部刷新)
    getCustomerOrgTree(oprType, body) {
      // getapi("/api/app/customerorg/getbycodeall").then((res) => {
      //   //customerOrgTree = res.data;
      //   console.log("res.data", res.data);
      //   this.setData({ key: "customerOrg.customerOrgTree", value: res.data });
      //   tcdate(this.customerOrg.customerOrgTree);
      // });
      switch (oprType) {
        case "insert":
          let node = {
            id: body.id,
            displayName: body.displayName,
            parentId: body.parentId,
          };

          if (body.parentId) {
            let pNode = getTreeNode(this.customerOrg.customerOrgTree,"treeChildren","id",body.parentId);
            if (!pNode.treeChildren) this.$set(pNode, 'treeChildren', []);
            //pNode.treeChildren = [] 
            pNode.treeChildren.push(node);
            
          } else {
            this.customerOrg.customerOrgTree.push(node);
          }
          this.customerOrg.defaultExpandedKeys = []
          if(body.parentId){
            this.customerOrg.defaultExpandedKeys.push(body.parentId)
          }
          this.customerOrg.defaultExpandedKeys.push(body.id)
          this.customerOrg.treeCurrentNodekey = body.id;          
          //console.log("this.customerOrg.treeCurrentNodekey",this.customerOrg.treeCurrentNodekey);
          break;

        // "id": "3a0c5101-a6a6-e48a-36ec-33e7567a99e6",
        //   "displayName": "神豚集团",
        //   "parentId": null,
        //   "code": "00001",
        //   "treeChildren": [

        case "update":
          let node2 = getTreeNode(
            this.customerOrg.customerOrgTree,
            "treeChildren",
            "id",
            body.id
          );
          node2.displayName = body.displayName;
          break;

        case "delete":
          let lfind = -1;
          let pids = getTreePids(
            this.customerOrg.customerOrgTree,
            "treeChildren",
            "parentId",
            "id",
            body
          );
          //tree, childNodeName, pidName, idName, idVal  getTreeNode(this.customerOrg.customerOrgTree, "treeChildren", "id", body);
          console.log('pids',pids,body)
          if (!pids || pids.length < 2) {
            lfind = arrayExistObj(this.customerOrg.customerOrgTree, "id", body);
            if (lfind > -1) this.customerOrg.customerOrgTree.splice(lfind, 1);
          } else {
            let node3 = getTreeNode(
              this.customerOrg.customerOrgTree,
              "treeChildren",
              "id",
              pids[0]
            );
            //console.log('node3',node3)
            lfind = arrayExistObj(node3.treeChildren, "id", body);
            if (lfind > -1) node3.treeChildren.splice(lfind, 1);
          }
          break;
        default:
          break;
      }
    },

    onkeyup(e){
      console.log('onkeyup e',e)
    },

    //提交
    btnSubmit(formName) {
      let body = {};
      console.log("vuex data", this.customerOrg.customerOrgRd);
      this.$refs[formName].validate((valid, fields) => {
        if (!valid) {
          this.$message.warning(fields[Object.keys(fields)[0]][0].message);
          return false;
        }

        body = deepCopy(this.form);
        delete body.isActiveBox;
        delete body.isLockBox;
        delete body.creatorName;
        delete body.creationTime;
        delete body.lastModifierName;
        delete body.lastModificationTime;

        if (typeof body.parentId === "string") {
          if (!body.parentId || body.parentId.length < 1) {
            body.parentId = null;
          }
        } else {
          if (body.parentId && body.parentId.length > 0) {
            body.parentId = body.parentId[body.parentId.length - 1];
          } else {
            body.parentId = null;
          }
        }

        console.log("body", body, "this.form", this.form);

        if (!this.customerOrg.customerOrgRd.id) {
          //id为空则新增
          postapi(`/api/app/customerorg/create`, body).then((res) => {
            if (res.code == 1) {
              console.log("创健 操作成功");
              //this.setData({ key: "customerOrg.customerOrgRd", value: res });
              this.customerOrg.customerOrgId = res.data.id;
              this.customerOrg.customerOrgRd = res.data;
              this.getCustomerOrgTree("insert", res.data);
              this.customerOrg.oprStatus = 'edit'
            }
          });
        } else {
          //id不为空则编辑
          putapi(`/api/app/customer-org/${this.customerOrg.customerOrgRd.id}`, body).then(
            (res) => {
              if (res.code == 1) {
                console.log("更新 操作成功");
                let lbody = { id: this.customerOrg.customerOrgRd.id, ...body };
                this.getCustomerOrgTree("update", lbody);
                this.customerOrg.oprStatus = 'edit'
              }
            }
          );
        }
      });
    },
    //新增弹框
    async add(formName, child) {
      await this.$refs[formName].resetFields();
      //console.log('this.peisid',this.peisid)
      if(!this.peisid || this.peisid == 'null'){
        this.$message.warning("该用户未选归属体检中心，不能执行此操作！");
        return
      }

      if (child) {
        if (!this.customerOrg.customerOrgId) {
          this.$message.warning("请先选择上级单位");
          this.customerOrg.oprStatus = ''
          return;
        }
        this.customerOrg.customerOrgRd.id = "";
        this.customerOrg.customerOrgRd = {
          id: "",
          isLock: "N",
          isActive: "Y",
          parentId: this.customerOrg.customerOrgId,
        };
      } else {
        this.customerOrg.customerOrgRd = {
          id: "",
          isLock: "N",
          isActive: "Y",
          parentId: null,
        };
      }
      this.customerOrg.oprStatus = 'add'

      objCopy(this.customerOrg.customerOrgRd, this.form);
      this.customerOrg.customerOrgId = "";
    },

    //删除
    del(formName) {
      if(!this.customerOrg.customerOrgRd.id){
        this.$message.warning("请先选中要删除的节点")
        return
      }
      //复制待删除的节点
      //let node = deepCopy(getTreeNode(this.customerOrg.customerOrgTree,"treeChildren","id",this.customerOrg.customerOrgRd.id));

      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }).then(() => {
        //console.log('{patientRegisterIds}',{patientRegisterIds})
        return deletapi(`/api/app/customer-org/${this.customerOrg.customerOrgRd.id}`);
      }).then((res) => {
        if (res.code != -1) {
          console.log("删除 操作成功");
          this.getCustomerOrgTree("delete", this.customerOrg.customerOrgRd.id);            
          this.customerOrg.customerOrgRegisterList = []         
          this.customerOrg.contactPersonList = []
          this.customerOrg.contactMethodList = []
          this.setData({ key: "customerOrg.customerOrgRd", value: { id: "" } });            
          this.$refs[formName].resetFields();
          this.customerOrg.oprStatus = ''
          this.customerOrg.customerOrgId = ''
        }
      }).catch((err) => {
        if (err == "cancel") {
          this.$message.info("已取消删除");
        } else {
          this.$message.error("操作失败，原因：" + err);
        }
      });
    },
    
    //回车替代tab键
    enterToTab() {
      this.$nextTick(() => {
        let inputs = document.querySelectorAll("form input"); //用数组可以读取多个标签的元素  //.inline-input
        //console.log('inputs',inputs);
        // 为每个输入框添加键盘事件监听器
        inputs.forEach((input,i) => {
          
          input.addEventListener('keydown', (event) => {
            
            // 如果按下的是回车键
            // console.log('data-ismultiline',input.getAttribute('data-ismultiline'));

            if (event.keyCode === 13) {
              // 阻止回车键的默认行为（换行）
              event.preventDefault();   
              
              // 跳至下一个输入框
              for(let j=i+1; j<inputs.length;j++){
                if(inputs[j].getAttribute('disabled') != "disabled" ){
                  inputs[j].focus();
                  break;
                }
              }              
            }
          });
        });
      });
    }, 
  },

  watch: {
    id(newVal, oldVal) {
      console.log("watch getCustomerOrgRd ", newVal, oldVal);
      if (newVal != oldVal && newVal != "") {
        this.getCustomerOrgRd(newVal);
      }
    },
  },
};
</script>
<style scoped>
@import "../../assets/css/global_form.css";
@import "../../assets/css/global_button.css";




.btnList {
  margin-bottom: 10px;
}

.btnClass {
  width: 110px;
}
</style>
