<template>
  <div style="display:flex;">
    <div> <!--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 - 655) / 3) + 'px;'">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位名称" prop="displayName">
              <el-input v-model="form.displayName" placeholder="请输入单位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位简称" prop="shortName">
              <el-input v-model="form.shortName" placeholder="请输入单位简称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="体检中心" prop="organizationUnitId">
              <el-select v-model="form.organizationUnitId" placeholder="请选择" filterable
                :style="'width:' + Math.floor((window.pageWidth - 655) / 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 v-model="form.orgTypeId" placeholder="请选择" filterable
                :style="'width:' + Math.floor((window.pageWidth - 655) / 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 v-model="form.telephone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="传真" prop="fax">
              <el-input v-model="form.fax" placeholder="请输入传真" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮政编码" prop="postalCode">
              <el-input 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 v-model="form.invoiceName" placeholder="请输入发票抬头" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开户银行" prop="bank">
              <el-input v-model="form.bank" placeholder="请输入开户银行" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="银行账号" prop="accounts">
              <el-input 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 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 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.creatorName" 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 class="btnList">
        <el-button type="primary" @click="add('form','')" class="btnClass">新增单位</el-button>
      </div>
      <div class="btnList">
        <el-button type="primary" @click="add('form','child')" class="btnClass">新增子单位</el-button>
      </div>
      <div class="btnList">
        <el-button type="success" @click="Onsubmit('form')" class="btnClass">保存</el-button>
      </div>
      <div class="btnList">
        <el-button type="danger" @click="del" class="btnClass">删除</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { tcdate, objCopy, deepCopy } from "../../utlis/proFunc";

export default {
  components: {},
  props: ['id'],
  data() {
    return {
      isActiveBox: false,
      customerOrgEditStyle: "height:400px;",
      data: {
        organizationdata: [], //体检中心数据
        customerOrgType: [], //单位类别
      },

    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,
      }, //初始化  单位 记录 目前新增与更新是一致

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

      isshow: false,
    };
  },

  created() {
    
  },

  //挂载完成
  mounted() {
    //获取体中心字典数据
    this.getoraniztion();

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

    this.getCustomerOrgRd(this.id);

  },

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

    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() {
      getapi("/api/app/customer-org/by-code-all").then((res) => {
        //customerOrgTree = res.data;
        console.log("res.data", res.data);
        this.setData({ key: "customerOrg.customerOrgTree", value: res.data });
        tcdate(this.customerOrg.customerOrgTree);
      });
    },

    //提交
    Onsubmit(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;

        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.length < 1) {
          //id为空则新增
          postapi(`/api/app/customer-org`, body).then((res) => {
            if (res.code == 1) {
              this.$message.success("创健 操作成功");
              this.setData({ key: "customerOrg.customerOrgRd", value: res });
              this.customerOrg.customerOrgId = res.id;
              this.customerOrg.customerOrgRd = res;
              this.getCustomerOrgTree();
            }
          });
        } else {
          //id不为空则编辑
          putapi(
            `/api/app/customer-org/${this.customerOrg.customerOrgRd.id}`,
            body
          ).then((res) => {
            if (res.code == 1) {
              this.$message.success("更新 操作成功");
              this.getCustomerOrgTree();
            }
          });
        }

      });
    },
    //新增弹框
    async add(formName,child) {

      await this.$refs[formName].resetFields();

      if (child) {
        if (!this.customerOrg.customerOrgId) {
          this.$message.info("请先选择单位")
          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.customerOrgId = "";

    },

    //删除
    del() {
      deletapi(
        `/api/app/customer-org/${this.customerOrg.customerOrgRd.id}`
      ).then((res) => {
        this.$message.success("删除 操作成功");
        this.setData({ key: "customerOrg.customerOrgRd", value: { id: "" } });
        this.getCustomerOrgTree();
      });
    },
  },

  watch: {
    'id'(newVal, oldVal) {
      console.log("watch getCustomerOrgRd newVal：", newVal, " oldVal：", oldVal);
      if (newVal != oldVal && newVal != '') {
        this.getCustomerOrgRd(newVal);
      }
    },
  },
};
</script>
<style scoped>
::v-deep .el-form-item {
  margin-bottom: 5px;
}

.btnList {
  margin-bottom: 10px;
}

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