<template>
  <div>
    <PageTable ref="companyTable" action="OrgMgQueryCompany" :columns="columns">
      <Form :model="formSearch" slot="search-bar" label-position="top" ref="orgFormSearch" class="ivu-form-no-margin-bottom" inline>
        <Form-item prop="companyName" :label="$t('module.orgManage.orgName')">
          <Input type="text" size="small" v-model="formSearch.companyName" maxlength="30" :placeholder="$t('module.orgManage.enterName')" ></Input>
        </Form-item>
        <Form-item prop="companyCode" :label="$t('module.orgManage.orgCode')">
          <Input type="text" size="small"  v-model="formSearch.companyCode" maxlength="30" :placeholder="$t('module.orgManage.enterCode')" ></Input>
        </Form-item>
      </Form>
      <div slot="handle-bar">
        <Button @click.native="search" type="warning" size="small"  icon="ios-search">{{$t('common.search')}}</Button>
        <Button @click.native="formReset" type="info"  size="small" icon="md-sync">{{$t('common.reset')}}</Button>
      </div>
      <Button slot="table-bar" type="ghost" icon="plus-round" @click="add">{{$t('common.create')}}</Button>
      <Button slot="table-bar" type="ghost" icon="trash-a" @click="deleted()">{{$t('common.delete')}}</Button>
    </PageTable>
    <Modal v-model="modal" width="600">
      <p slot="header">
        <span>{{ companyWinTitle }}</span>
      </p>
      <div>
        <Form :model="formInfo" ref="companyForm" :rules="rules" :label-width="80">
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.orgManage.orgName')" prop="companyName">
              <Input placeholder=""  v-model="formInfo.companyName"></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.orgManage.orgCode')" prop="companyCode">
              <Input placeholder="" v-model="formInfo.companyCode"></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.orgManage.orgType')" prop="orgDimensionCode">
              <Select v-model="formInfo.orgDimensionCode" class="no-borderColor" >
                <Option v-for="itemKey in Object.keys(orgDimensionDic)" :value="itemKey" :key="itemKey">{{ orgDimensionDic[itemKey] }}</Option>
              </Select>
            </Form-item>
            </Col>
          </Row>
          <!-- 此需求又被去掉啦，啦啦啦
            <Row :gutter="20" class="code-row-bg">
              <Col span="24">
              <Form-item ::label="关联组织" prop="referenceCompanyId">
                <Select v-model="formInfo.referenceCompanyId" filterable>
                  <Option v-for="item in allReferenceCompany" :value="item.companyId" :key="item.companyId">{{ item.companyName }}</Option>
                </Select>
              </Form-item>
              </Col>
            </Row>
            -->
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.orgManage.orgDesc')" prop="companyDesc">
              <Input placeholder="" type="textarea" :rows="4" maxlength="200" v-model="formInfo.companyDesc"></Input>
            </Form-item>
            </Col>
          </Row>

        </Form>
      </div>
      <div slot="footer" class="run-modal-ftbButton">
        <Button type="primary" @click="onOk()">{{$t('common.confirm')}}</Button>
      </div>
    </Modal>
  </div>
</template>
<style>
.no-borderColor .ivu-select-selection{
  border-color: #dddee1 !important;
}
</style>
<script>
// import data from '../../assets/data/menuThree.json'
import Three from "../../../tools/getThree.js";
import OrgTreeManagePage from "./OrgTreeManage.vue";
export default {
  name: 'org-manage',
  components: {},
  data() {

    const validateCompanyCode = (rule, value, callback) => {
      // if (value === "") {
      //   callback(new Error("请输入组织编码"));
      // } else 
      if (value.length > 50) {
        callback(new Error(this.$t('module.orgManage.codeMaxFifty')));
      } else if (!new RegExp("^[a-zA-z0-9]+$").test(value)) {
        callback(new Error(this.$t('module.orgManage.codeContain')));
      }
      callback();
    };
    const validateCompanyName = (rule, value, callback) => {
      // if (value === "") {
      //   callback(new Error("请输入组织名称"));
      //   } else
      if (value != value.trim()) {
        callback(new Error(this.$t('module.orgManage.noBalnk')));
      } else if (value.length > 50) {
        callback(new Error(this.$t('module.orgManage.nameMaxFifty')));
      }
      callback();
    };
    const validateCompanyDesc = (rule, value, callback) => {
      if (value != null && value != value.trim() && value.trim() === "") {
        callback(new Error(this.$t('module.orgManage.enterLegalDesc')));
      }
      if (value != null && value.length > 200) {
        callback(new Error(this.$t('module.orgManage.descMaxTH')));
      }
      callback();
    };

    return {
      modal: false,
      loadingCompany: false,
      tableData: [],
      companyWinTitle: this.$t('module.orgManage.addNewOrg'),
      formInfo: {
        companyName: "",
        companyCode: "",
        companyDesc: "",
        companyId: "",

        referenceCompanyId: "",
        orgDimensionCode: ""
      },
      rules: {
        companyCode: [
          { required: true, message: this.$t('module.orgManage.enterCode'), trigger: "blur" },
          { validator: validateCompanyCode, trigger: "blur" },
        ],
        companyName: [
          { required: true, message: this.$t('module.orgManage.enterName'), trigger: "blur" },
          { validator: validateCompanyName, trigger: "blur" },
        ],
        orgDimensionCode: [
          { required: true, message: this.$t('module.orgManage.selectOrgType'), trigger: "blur, change" },
        ],
        companyDesc: [
          { validator: validateCompanyDesc, trigger: "blur" },
        ]
      },
      baseData: [],
      formSearch: {
        companyName: "",
        companyCode: ""
      },
      columns: [
        {
          type: "selection",
          width: 40,
          align: "center",
          fixed: 'left',
        },
        {
          title: this.$t('common.operating'),
          align: "center",
          width: 120,
          fixed: 'left',
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: [
                  {
                    type: "icon",
                    icon: "md-create",
                    text: this.$t('common.edit'),
                    handle: () => {
                      this.modal = true;
                      this.$nextTick(function () {
                        this.companyWinTitle = this.$t('module.orgManage.editOrg');
                        this.resetForm();
                        this.formInfo = {
                          companyName: params.row.companyName,
                          companyCode: params.row.companyCode,
                          companyDesc: params.row.companyDesc,
                          companyId: params.row.companyId,

                          referenceCompanyId: params.row.referenceCompanyId ? params.row.referenceCompanyId : '',
                          orgDimensionCode: params.row.orgDimensionCode,
                          version: params.row.version
                        };
                      });
                    }
                  },
                  {
                    type: "button",
                    text: this.$t('module.orgManage.orgMaintain'),
                    handle: () => {
                      new this.$sidelipPage(OrgTreeManagePage, {
                        props: {
                          companyId: params.row.companyId,
                          companyName: params.row.companyName,
                          companyCode: params.row.companyCode
                          //,
                          //referenceCompanyId: params.row.referenceCompanyId,
                          //referenceCompanyName: params.row.referenceCompanyName
                        }
                      });
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: this.$t('module.orgManage.orgName'),
          key: "companyName",
          sortable: "custom",
          width: 130,
          align: "center",
          render: (h, params) => {
            return h('span', {
              attrs: {
                title: params.row.companyName
              },
            }, params.row.companyName);
          }
        },
        {
          title: this.$t('module.orgManage.orgCode'),
          sortable: "custom",
          align: "center",
          key: "companyCode",
          width: 130,
          render: (h, params) => {
            return h('span', {
              attrs: {
                title: params.row.companyCode
              },
            }, params.row.companyCode);
          }
        },
        {
          title: this.$t('module.orgManage.orgType'),
          sortable: "custom",
          width: 130,
          align: "center",
          key: "orgDimensionCode",
          render: (h, params) => {
            return h('span', this.orgDimensionDic[params.row.orgDimensionCode]);
          }
        },
        {
          title: this.$t('module.orgManage.createTime'),
          sortable: "custom",
          width: 130,
          key: "createTime"
        },
        {
          title: this.$t('module.orgManage.updateTime'),
          sortable: "custom",
          align: "center",
          width: 130,
          key: "updateTime"
        },
        {
          title: this.$t('module.orgManage.orgDesc'),
          width: 130,
          key: "companyDesc",
          align: "center",
          render: (h, params) => {
            return h('span', {
              attrs: {
                title: params.row.companyDesc
              },
            }, params.row.companyDesc);
          }
        },
      ],
      orgDimensionDic: {},//组织维度
      allReferenceCompany: [],  //关联组织数组
    };
  },
  computed: {},
  created: function () {

    this.QueryOrgDimension();
    //关联组织需求，已被取消-2017/12/07
    //this.QueryAllCompany();

  },
  beforeMount: function () { },
  mounted: function () { },
  beforeDestroy: function () { },
  destroyed: function () { },
  methods: {
    search() {
      this.$refs["companyTable"].load(this.formSearch);
    },
    formReset() {
      this.$refs["orgFormSearch"].resetFields();
      this.$refs["companyTable"].load(this.formSearch);
    },
    deleted() {
      let deleteStr = this.getIds();
      if (deleteStr == "" || deleteStr == undefined) {
        this.$Message.warning({
          content: this.$t('module.orgManage.selectOrg'),
          duration: 3
        });
        return;
      }
      new $confirm(this.$t('module.orgManage.confirmDelete'), this).then(() => {
        this.$store
          .dispatch("OrgMgDeleteCompany", {
            companyIds: deleteStr
          })
          .then(response => {
            if (response.statusCode != 0) {
              this.$Message.warning({
                content: response.msg,
                duration: 3
              });
              return;
            }
            this.$Message.warning({
              content: this.$t('module.orgManage.deleteSuccess'),
              duration: 3
            });

            this.search();
          });
      });
    },
    add() {
      this.resetForm();
      this.companyWinTitle = this.$t('module.orgManage.addNewOrg');
      this.modal = true;
      this.formInfo = {
        companyName: "",
        companyCode: "",
        companyDesc: "",
        companyId: "",
        referenceCompanyId: "",
        orgDimensionCode: ""

      };

      // this.QueryAllCompany('');
    },
    onOk() {
      this.$refs["companyForm"].validate(valid => {
        if (valid) {
          if (this.formInfo.companyId) {
            this.$store
              .dispatch("OrgMgUpdateCompany", this.formInfo)
              .then(response => {
                this.modal = false;
                if (response.statusCode == "0") {
                  this.search();
                } else {
                  this.$Message.warning({
                    content: response.msg,
                    duration: 3
                  });
                }
              });
          } else {
            this.$store
              .dispatch("OrgMgAddCompany", this.formInfo)
              .then(response => {
                if (response.statusCode == "0") {
                  this.modal = false;
                  this.search();
                } else {
                  this.$Message.warning({
                    content: response.msg,
                    duration: 3
                  });
                }
              });
          }
        } else {
          this.$Message.error(this.$t('common.formValidateFailed'));
        }
      });
    },
    getIds() {
      let list = this.$refs["companyTable"].getSelectioned() || [];
      let ids = [];
      for (let u of list) {
        ids.push(u.companyId);
      }
      return ids.join(",");
    },
    resetForm() {
      this.$refs["companyForm"].resetFields();
    },
    QueryOrgDimension() {
      //获取组织维度
      this.$store
        .dispatch("GetValueSetByCode", {
          code: 'orgDimension'
        })
        .then(response => {
          this.orgDimensionDic = {};
          let dicArray = response.dataResult;
          for (let i = 0; i < dicArray.length; i++) {
            let dic = dicArray[i];
            this.orgDimensionDic[dic.vsiKey] = dic.vsiValue;
          }
        });
    },
    QueryAllCompany() {
      //获取所有的组织主记录，为添加及维护主记录时关联组织使用
      this.loadingCompany = true;
      this.$store
        .dispatch("OrgMgQueryCompany", {
          commonPageDTO: { currentPage: 1, pageSize: 1000 }
        })
        .then(response => {
          this.allReferenceCompany = [];
          this.loadingCompany = false;
          this.allReferenceCompany = response.recordList;
        });
    }
  },
  watch: {},
  directives: {}
};
</script>
