<template>
  <div>
    <FormBlock :title="$t('module.chooseOrg.choosable')">
      <PageTable ref="companyTable" action="OrgMgQueryCompany" :columns="columns">
        <Form :model="formSearch" slot="search-bar" label-position="top" class="ivu-form-no-margin-bottom" inline>
          <Form-item :label="$t('module.chooseOrg.compName')" style="width: 51%">
              <Input type="text" v-model="formSearch.companyName" :placeholder="$t('module.chooseOrg.enterName')" size="small"></Input>
            </Form-item>             
            <Form-item :label="$t('module.chooseOrg.compCode')" style="width: 51%">
              <Input type="text" v-model="formSearch.companyCode" :placeholder="$t('module.chooseOrg.enterCode')" size="small"></Input>
            </Form-item>
        </Form>
        <div slot="handle-bar">
          <Button size="small" @click.native="search" type="warning" icon="ios-search">{{$t('common.search')}}</Button>
          <Button size="small" @click.native="reset" type="info" icon="md-sync">{{$t('common.reset')}}</Button>
        </div>
      </PageTable>
    </FormBlock>
    <Modal v-model="modal" width="600">
      <p slot="header">
        <span>{{$t('module.chooseOrg.selectDepartment')}}</span>
      </p>
      <div>
        <el-tree :data="baseData" :props="{
        children: 'children',
        label: 'orgName'
      }" show-checkbox :load="loadNode" @check-change="checkChange" :check-strictly="true" empty-text="" highlight-current lazy node-key="orgId" ref="chooseOrgTree" :expand-on-click-node="false">
        </el-tree>
      </div>
      <div slot="footer" class="run-modal-ftbButton">
        <!-- <Button type="primary" @click="onOk()">确定</Button> -->
      </div>
    </Modal>
  </div>
</template>
<script>
import Three from "../../tools/getThree.js";
import ChooseOrgTree from "./ChooseOrgTree.vue";
export default {
  components: {},
  props: {
    originalOrgIds: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    const validateCompanyCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t('module.chooseOrg.enterCode')));
      } else if (value.length > 50) {
        callback(new Error(this.$t('module.chooseOrg.codeMaxFifty')));
      } else if (!new RegExp("^[a-zA-z0-9]+$").test(value)) {
        callback(new Error(this.$t('module.chooseOrg.codeContain')));
      }
      callback();
    };
    const validateCompanyName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t('module.chooseOrg.enterName')));
      } else if (value != value.trim()) {
        callback(new Error(this.$t('module.chooseOrg.nameNoblank')));
      } else if (value.length > 50) {
        callback(new Error(this.$t('module.chooseOrg.nameMaxFifty')));
      }
      callback();
    };
    const validateCompanyDesc = (rule, value, callback) => {
      if (value != null && value != value.trim() && value.trim() === "") {
        callback(new Error(this.$t('module.chooseOrg.enterLegalDesc')));
      }
      if (value != null && value.length > 200) {
        callback(new Error(this.$t('module.chooseOrg.descMaxTH')));
      }
      callback();
    };

    return {
      modal: false,
      tableData: [],
      orgIds: [],
      companyWinTitle: this.$t('module.chooseOrg.addNewComp'),
      formInfo: {
        companyName: "",
        companyCode: "",
        companyDesc: "",
        companyId: ""
        // createTime: '',
        // createUserId: '',
        // updateTime: '',
        // updateUserId: '',
      },
      rules: {
        companyCode: [{ validator: validateCompanyCode, trigger: "blur" }],
        companyName: [{ validator: validateCompanyName, trigger: "blur" }],
        companyDesc: [{ validator: validateCompanyDesc, trigger: "blur" }]
      },
      baseData: [],
      companyName: "",
      companyId: "",
      defaultCheckedKeys: [],
      formSearch: {
        companyName: "",
        companyCode: ""
      },
      columns: [
        {
          title: this.$t('common.operating'),
          align: "center",
          width: 120,
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: [
                  {
                    type: "button",
                    text: this.$t('module.chooseOrg.selectDepartment'),
                    handle: () => {
                      this.companyId = params.row.companyId;
                      this.companyName = params.row.companyName;
                      this.baseData = [
                        {
                          orgName: this.companyName,
                          orgId: "0",
                          children: [],
                          parentId: -1,
                          disabled: true
                        }
                      ];
                      this.defaultCheckedKeys = [];
                      for (let item of this.orgIds) {
                        this.defaultCheckedKeys.push(item.orgId);
                      }
                      this.modal = true;

                      // this.$refs["chooseOrgTree"].setCheckedNodes(checked);
                      // new this.$sidelipPage(ChooseOrgTree, {
                      //   props: {
                      //     companyId: params.row.companyId,
                      //     companyName: params.row.companyName
                      //   }
                      // });
                      //this.edit(params.row.roleId)
                      // this.$router.push(`/app/org-tree-manage?orgId=${params.row.orgId}`);
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: this.$t('module.chooseOrg.compName'),
          key: "companyName"
        },
        {
          title: this.$t('module.chooseOrg.compCode'),
          key: "companyCode"
        },
        {
          title: this.$t('module.chooseOrg.compDesc'),
          key: "companyDesc"
        }
      ]
    };
  },
  computed: {},
  created: function () {
    // this.$emit("SetPageActions", [
    //   {
    //     text: this.$t('common.save'),
    //     theme: "info",
    //     icon: "md-create",
    //     handle: this.save
    //   }
    // ]);
    this.$emit("setTitle", this.$t('module.chooseOrg.selectDepartment'));
  },
  beforeMount: function () { },
  mounted: function () {
    for (let o of this.originalOrgIds) {
      this.orgIds.push(o);
    }
  },
  beforeDestroy: function () { },
  destroyed: function () { },
  methods: {
    save() {
      this.$emit("handler", null);
    },
    search() {
      this.$refs["companyTable"].load(this.formSearch);
    },
    reset() {
      this.formSearch.companyName = "";
      this.formSearch.companyCode = "";
      this.$refs["companyTable"].load(this.formSearch);
    },
    checkChange(data) {
      this.modal = false;
      // setTimeout(() => {
        this.$emit("handler", data);
        this.$emit("Close");
      // }, 500);
    },
    onOk() {
      let checked = this.$refs["chooseOrgTree"].getCheckedNodes();
      for (let item of checked) {
        let i = this.orgIds.findIndex(v => {
          return v.orgId == item.orgId;
        });
        if (i < 0) {
          this.orgIds.push(item);
        }
      }
      this.modal = false;
    },
    resetForm() {
      this.$refs["companyForm"].resetFields();
    },
    handleClose(index) {
      this.orgIds.splice(index, 1);
    },
    loadNode(node, resolve) {
      // let checked = node.checked;
      // node.checked = false; //每次加载，均取消当前功能的复选框选中状态
      this.node = node;
      //
      if (node.level == 0) {
        resolve(this.baseData);
        return;
      }
      let parentId = 0;
      if (node.level != 0) {
        parentId = node.data.orgId;
      }

      $store
        .dispatch("OrgMgQueryOrgListByCompanyId", {
          companyId: this.companyId,
          parentId: parentId,
          sortDTO: {
            fieldName: "",
            orderBy: ""
          }
        })
        .then(res => {
          if (res.statusCode != 0) {
            this.$Message.warning({
              content: res.msg,
              duration: 3
            });
            return;
          }
          //this.baseData = res.dataResult;
          resolve(res.dataResult);
        });

      //node.checked = checked;
    }
  },
  watch: {},
  directives: {}
};
</script>
