<template>
  <div
    class="es-sizer"
    :style="styles"
    v-loading="loading"
    element-loading-text="处理中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.65)"
  >
    <es-tree
      :param="params"
      :parseParams="handleParams"
      :url="url"
      ref="sizerTree"
      show-search
      show-checkbox
      check-strictly
      @check-change="handleChange"
    ></es-tree>
    <div class="es-sizer-handle">
      <es-button size="medium" @click="handleCheckedAll">全选</es-button>
      <es-button size="medium" @click="handleResetChecked">全清</es-button>
      <es-button
        size="medium"
        @click="handleAllSub"
        :type="checkType === 'checksubAllTrue' ? 'primary' : ''"
        >所有下级</es-button
      >
      <es-button
        size="medium"
        @click="handleSub"
        :type="checkType === 'checksubTrue' ? 'primary' : ''"
        >直接下级</es-button
      >
    </div>
    <div class="handleBox">
      <es-button size="medium" type="primary" @click="handleConfirm"
        >确认</es-button
      >
      <es-button size="medium" @click="handleCancel">取消</es-button>
    </div>
  </div>
</template>
<script>
import { getOrgMainTree, getSelectOrgsubids } from 'eoss-ui/src/config/api.js';
import util from 'eoss-ui/src/utils/util';
export default {
  name: 'EsSizer',
  inject: {
    esDialog: {
      default: ''
    }
  },
  props: {
    method: {
      type: String,
      default: 'get'
    },
    width: {
      type: [String, Number],
      default: '500px'
    },
    height: {
      type: [String, Number],
      default: '600px'
    },
    url: {
      type: String,
      default: getOrgMainTree
    },
    orgUrl: {
      type: String,
      default: getSelectOrgsubids
    },
    selectField: {
      type: String,
      default: 'creditCode'
    },
    businessSubCentercode: String,
    param: {
      type: Object,
      default() {
        return {
          showarea: 0,
          orgType: 'org',
          nocheck: false,
          id: 'all',
          isroot: true,
          businessSubCentercode: 'business_property',
          synchro: true,
          pvd: 'true',
          levels: 2,
          showlevelsub: true,
          selectType: 'orglist'
        };
      }
    }
  },
  computed: {
    styles() {
      if (this.esDialog) {
        return { height: '100%' };
      }
      let width = this.width;
      let height = this.height;
      if (typeof this.width === 'number' || this.width.indexOf('px') === -1) {
        width = this.width + 'px';
      }
      if (typeof this.height === 'number' || this.height.indexOf('px') === -1) {
        height = this.height + 'px';
      }
      return { width: width, height: height };
    },
    params() {
      if (this.businessSubCentercode) {
        return {
          ...this.param,
          businessSubCentercode: this.businessSubCentercode
        };
      }
      return this.param;
    }
  },
  watch: {
    checkeds: {
      deep: true,
      handler(val) {
        this.$emit('change', val);
      }
    }
  },
  data() {
    return {
      loading: false,
      checkeds: null,
      checkType: null
    };
  },
  created() {
    //this.loadsub(this.param);
  },
  methods: {
    handleParams({ data, params }) {
      let param = JSON.parse(JSON.stringify(params));
      param.isroot = data.pId === 'root';
      return param;
    },
    handleCheckedAll() {
      this.$refs.sizerTree.handleCheck();
      this.checkType = 'checkAllTrue';
    },
    handleResetChecked() {
      this.$refs.sizerTree.setCheckedKeys([]);
      this.checkType = null;
    },
    getCheckedNodes() {
      this.checkeds = this.$refs.sizerTree.getCheckedNodes();
      return this.checkeds;
    },
    handleChange() {
      this.getCheckedNodes();
    },
    handleAllSub() {
      if (!this.checkeds || !this.checkeds.length) {
        this.$alert('请选择组织!', '提示', {
          type: 'warning'
        });
      } else {
        this.checkType = 'checksubAllTrue';
      }
    },
    handleSub() {
      if (!this.checkeds || !this.checkeds.length) {
        this.$alert('请选择组织!', '提示', {
          type: 'warning'
        });
      } else {
        this.checkType = 'checksubTrue';
      }
    },
    async handleConfirm() {
      if (!this.checkeds || !this.checkeds.length) {
        this.$alert('请选择组织!', '提示', {
          type: 'warning'
        });
      } else {
        let ids = [];
        let creditCodes = [];
        let carry = true;
        if (this.checkType === 'checkAllTrue') {
          ids = ['all'];
        } else {
          this.checkeds.forEach((item) => {
            let data = item.data.objdata
              ? JSON.parse(item.data.objdata)
              : item.data;
            if (data[this.selectField] && data[this.selectField] !== 'undefined') {
              creditCodes.push(data[this.selectField]);
            }
            if (item.isParent && item.children) {
              ids.push(item.id);
            }
          });
        }
        if (this.checkType) {
          let params = {
            businessSubCentercode:
              this.params.businessSubCentercode ||
              this.params.requestbusinessSubCentercode,
            selectIds: ids.join(','),
            selectField: this.selectField,
            checkType: this.checkType
          };
          this.loading = true;
          await util
            .ajax({
              url: this.orgUrl,
              method: this.method,
              data: params,
              params: params
            })
            .then((res) => {
              this.loading = false;
              if (res.rCode === 0) {
                creditCodes = creditCodes.concat(res.results.split(','));
              } else {
                carry = false;
                this.$alert('查询出错，请联系系统管理员', '提示', {
                  type: 'error'
                });
              }
            })
            .catch((err) => {
              this.loading = false;
              if (err.message && err.message !== 'canceled') {
                this.$message.error(err.message);
              }
            });
        }
        if (carry) {
          this.$emit('confirm', {
            checkeds: this.checkeds,
            [this.selectField]: creditCodes.join(','),
            selectIds: ids,
            count: creditCodes.length
          });
          this.esDialog && this.esDialog.handleClose();
        }
      }
    },
    handleCancel() {
      this.$emit('cancel');
      this.esDialog && this.esDialog.handleClose();
    }
  }
};
</script>
