<template>
  <div id="containt">
    <el-tabs v-model="activeName" class="tab-box">
      <el-tab-pane label="机构列表" name="second">
        <div class="grid-height">
          <vxe-grid ref="table-m1" v-bind="vxeOption" @resizable-change="$vxeTableUtil.onColumnWitchChange"
                    @custom="$vxeTableUtil.customHandle">
            <template #form>
              <div class="clearfix screen-btns">
                <div class="fl">
                  <base-table-export :option="{ title: $t1('机构导出'), targetRef: 'table-m1', conditionExport: false}"
                                     :parent-target="_self"/>
                </div>
                <div class="fr">
                  <vxe-button icon="el-icon-brush" class="button-sty" @click="resetEvent" type="text" status="primary"
                              plain>{{ $t1('重置') }}
                  </vxe-button>
                  <vxe-button status="warning" icon="el-icon-search" class="button-sty" @click="searchEvent">
                    {{ $t1('搜索') }}
                  </vxe-button>
                </div>
              </div>
              <vxe-form ref="form" class="screen-box" title-width="92px" title-align="right" :data="formData"
                        @submit="searchEvent">
                <vxe-form-item :title="$t1('机构名称')+':'" field="name">
                  <template v-slot>
                    <el-input v-model="formData.name" size="small" clearable/>
                  </template>
                </vxe-form-item>
                <vxe-form-item :title="$t1('机构编码')+':'" field="sn">
                  <template v-slot>
                    <el-input v-model="formData.sn" size="small" clearable/>
                  </template>
                </vxe-form-item>
                <vxe-form-item :title="$t1('第三方机构编码')+':'" field="outSn">
                  <template v-slot>
                    <el-input v-model="formData.outSn" size="small" clearable/>
                  </template>
                </vxe-form-item>
                <vxe-form-item :title="$t1('是否启用')+':'" field="enabled">
                  <template v-slot>
                    <el-select v-model="formData.enabled" clearable>
                      <el-option value="true" :label="$t1('启用')"></el-option>
                      <el-option value="false" :label="$t1('禁用')"></el-option>
                    </el-select>
                  </template>
                </vxe-form-item>
              </vxe-form>
            </template>
            <template #operate="obj">
              <div class="cell-operate">
                <template v-if="$refs['table-m1'].isActiveByRow(obj.row)">
                  <a @click="saveRowEvent(obj)" class="a-link">
                    <el-tooltip :enterable="false" effect="dark" :content="$t1('保存')" placement="top"
                                popper-class="tooltip-skin"><i class="el-icon-circle-check"></i></el-tooltip>
                  </a>
                  <a @click="cancleRowEvent(obj)" class="a-link" v-if="hasSaveRow(obj.row)">
                    <el-tooltip :enterable="false" effect="dark" :content="$t1('取消行编辑')" placement="top"
                                popper-class="tooltip-skin"><i class="el-icon-circle-close"></i></el-tooltip>
                  </a>
                  <a @click="removeRowEvent(obj)" class="a-link" v-if="!hasSaveRow(obj.row)">
                    <el-tooltip :enterable="false" effect="dark" :content="$t1('删除')" placement="top"
                                popper-class="tooltip-skin"><i class="el-icon-delete"></i></el-tooltip>
                  </a>
                </template>
                <template v-else>
                  <a class="a-link" @click="insertChildEvent(obj)">
                    <el-tooltip :enterable="false" effect="dark" :content="$t1('新增')" placement="top"
                                popper-class="tooltip-skin"><i class="el-icon-circle-plus-outline"></i></el-tooltip>
                  </a>
                  <a @click="editRowEvent(obj)" class="a-link" v-if="obj.row && obj.row.parent !== 0">
                    <el-tooltip :enterable="false" effect="dark" :content="$t1('行编辑')" placement="top"
                                popper-class="tooltip-skin"><i class="el-icon-edit-outline"></i></el-tooltip>
                  </a>
                  <!-- <a class="a-link" @click="openChangeParentDialog(obj)">
										<el-tooltip :enterable="false" effect="dark" content="切换上级机构" placement="top" popper-class="tooltip-skin">
											<i class="el-icon-office-building"></i>
										</el-tooltip>
									</a>
									<a class="a-link" @click="openSortRowDialog(obj)">
										<el-tooltip :enterable="false" effect="dark" content="排序修改" placement="top" popper-class="tooltip-skin"><i class="el-icon-sort"></i></el-tooltip>
									</a> -->
                </template>
              </div>
            </template>
            <template #director="{row,rowIndex,$table}">
              <el-input
                class="search-input"
                v-model="row.directorName"
                clearable
                @clear="
                    row.directorId = null;
                    $forceUpdate();
                  "
                v-el-readonly
              >
                <i slot="suffix" class="el-input__icon el-icon-search" @click="openDirectorDialog(row)"></i>
              </el-input>
            </template>
            <template #role="{row,rowIndex,$table}">
              <el-input
                class="search-input"
                v-model="row.roleName"
                clearable
                @clear="
                    row.roleId = null;
                    $forceUpdate();
                  "
                v-el-readonly
              >
                <i slot="suffix" class="el-input__icon el-icon-search" @click="openRoleDialog(row)"></i>
              </el-input>
            </template>
            <template #area="{row,rowIndex,$table}">
              <el-input
                class="search-input"
                v-model="row.areaName"
                clearable
                @clear="
                    row.areaId = null;
                    $forceUpdate();
                  "
                v-el-readonly
              >
                <i slot="suffix" class="el-input__icon el-icon-search" @click="openAreaDialog(row)"></i>
              </el-input>
            </template>
          </vxe-grid>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      :title="$t1('切换上级机构')"
      :append-to-body="true"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="showChangeParentDialog"
      :modal="false"
      :destroy-on-close="true"
      custom-class="dialog-style list-dialog"
      width="300px"
      v-el-drag-dialog
    >
      <div class="cont">
        <el-form :model="changeForm1">
          <el-form-item :label="$t1('当前机构')">
            <el-input v-model="changeForm1.sale_org.name" autocomplete="off" readonly></el-input>
          </el-form-item>
          <el-form-item :label="$t1('上级机构')">
            <el-input
              class="search-input"
              max="200"
              v-model="changeForm1.parent.name"
              @clear="
                changeForm1.parent = '';
                $forceUpdate();
              "
              v-el-readonly
              clearable
            >
              <i slot="suffix" class="el-input__icon el-icon-search" @click="showSaleOrgDialog = true"></i>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain class="button-sty" @click="showChangeParentDialog = false">
          <i class="el-icon-close el-icon"></i>
          {{ $t1('取 消') }}
        </el-button>
        <el-button type="primary" @click="changeRowParent" class="button-sty">
          <i class="el-icon-check el-icon"></i>
          {{ $t1('确 定') }}
        </el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="$t1('排序')"
      :append-to-body="true"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="showSortRowDialog"
      :modal="false"
      :destroy-on-close="true"
      custom-class="dialog-style list-dialog"
      width="600px"
      v-el-drag-dialog
    >
      <div class="cont" style="height:400px;">
        <vxe-grid row-key ref="sortTable" v-bind="sortTableOption" class="sortable-tree-demo"
                  :scroll-y="{ enabled: false }"></vxe-grid>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain class="button-sty" @click="showSortRowDialog = false">
          <i class="el-icon-close el-icon"></i>
          {{ $t1('取 消') }}
        </el-button>
        <el-button type="primary" @click="saveSort" class="button-sty">
          <i class="el-icon-check el-icon"></i>
          {{ $t1('确 定') }}
        </el-button>
      </span>
    </el-dialog>
    <saleOrgDialog v-if="showSaleOrgDialog" :visiable.sync="showSaleOrgDialog" @confirm="confirmInsertSaleOrg"
                   multi="false"/>
    <userDialog v-if="showDirectorDialog" :visiable.sync="showDirectorDialog" @confirm="confirmInsertDirector"
                multi="false"/>
    <roleDialog v-if="showRoleDialog" :visiable.sync="showRoleDialog" @confirm="confirmInsertRole"
                multi="false"/>
    <areaDialog v-if="showAreaDialog" :visiable.sync="showAreaDialog" @confirm="confirmAreaDialog"
                multi="false"/>
  </div>
</template>
<script>
import Sortable from 'sortablejs';
import {tableTreeMixins} from '@base/mixins/tableTree/index.js';
import saleOrgDialog from '../../../views/user/sale_org/dialog.vue';
import userDialog from '../../../views/user/user/dialog'
import roleDialog from '../../../views/user/role/dialog'
import areaDialog from '../../../views/user/area/dialog'

export default {
  name: 'sale_org:list',
  components: {saleOrgDialog, userDialog, roleDialog, areaDialog},
  mixins: [tableTreeMixins],
  mounted() {
    this.initTableList();
  },
  data() {
    let that = this;
    return {
      value10: '',
      dataId: '',
      formData: {
        enabled: ''
      },
      vxeOption: {},
      activeName: 'second',
      changeForm1: {sale_org: '', parent: ''},
      changeForm2: {},
      showSaleOrgDialog: false,
      showChangeParentDialog: false,
      showSortRowDialog: false,
      showHelpTip2: false,
      sortRows: [],
      sortTableOption: {},
      showDirectorDialog: false,
      operateIndex: null,
      showRoleDialog: false,
      showAreaDialog: false
    };
  },
  beforeDestroy() {
    if (this.sortable1) {
      this.sortable1.destroy();
    }
  },
  methods: {
    searchEvent({$form}) {
      this.$refs['table-m1'].commitProxy('reload');
    },
    resetEvent() {
      this.formData = {};
      this.$refs['table-m1'].commitProxy('reload');
    },
    initTableList() {
      let that = this;
      let typeMap = {
        0: this.$t1('集团'),
        1: this.$t1('事业部'),
        2: this.$t1('分公司'),
        3: this.$t1('部门'),
        99: this.$t1('其他')
      }
      let tableOption = {
        vue: this,
        tableRef: 'table-m1',
        tableName: 'basic_sale_org_list-m1',
        path: USER_PREFIX + '/sale_org/getCurrentList',
        treeNodeUrl: USER_PREFIX + '/sale_org/getChildren',
        editSaveUrl: USER_PREFIX + '/sale_org/save',
        editDefaultRow: {enabled: true, directorName: null, directorId: null, roleName: null, roleId: null},
        param: () => {
          return this.formData;
        },
        treeNodeParam: row => {
          return {
            parent: row.id,
            enabled: this.formData.enabled
          };
        },
        columns: [
          {type: 'checkbox', width: 48, resizable: false, fixed: 'left'},
          {
            title: this.$t1('机构名称'),
            field: 'name',
            width: 250,
            fixed: 'left',
            treeNode: true,
            editRender: {name: 'input'},
            slots: {
              default: ({row}) => {
                return [
                  <a
                    class="levitate-tips"
                    onclick={(event) => {
                      event.stopPropagation();
                      this.$refs['table-m1'].toggleTreeExpand(row);
                    }}
                  >
                    {row.name}
                  </a>
                ];
              }
            }
          },
          {field: 'sn', title: this.$t1('机构编码'), width: 250, editRender: {name: 'input'}},
          {field: 'outSn', title: this.$t1('第三方机构编码'), width: 150, editRender: {name: 'input'}},
          {
            field: 'type',
            title: this.$t1('类型'),
            width: 150,
            editRender: {
              name: '$select',
              props: {clearable: true},
              events: {
                change: () => {
                  this.$forceUpdate();
                }
              },
              options: [
                {
                  label: typeMap[0],
                  value: 0
                },
                {
                  label: typeMap[1],
                  value: 1
                },
                {
                  label: typeMap[2],
                  value: 2
                },
                {
                  label: typeMap[3],
                  value: 3
                },
                {
                  label: typeMap[99],
                  value: 99
                }
              ]
            },
            slots: {
              default: ({row}) => {
                return typeMap[row.type] || '';
              }
            }
          },
          {
            field: 'enabled',
            title: this.$t1('是否启用'),
            width: 150,
            editRender: {
              name: '$select',
              props: {clearable: true},
              events: {
                change: () => {
                  this.$forceUpdate();
                }
              },
              options: [
                {
                  label: this.$t1('启用'),
                  value: true
                },
                {
                  label: this.$t1('禁用'),
                  value: false
                }
              ]
            },
            slots: {
              default: ({row}) => {
                if (row.enabled) {
                  return [<div class="txt-status">{this.$t1('启用')}</div>];
                } else {
                  return [<div class="txt-status s-3">{this.$t1('禁用')}</div>];
                }
              }
            }
          },
          {
            title: this.$t1('负责人'),
            field: 'directorName',
            width: 150,
            editRender: {name: 'input'},
            slots: {
              edit: 'director'
            }
          },
          {
            title: this.$t1('授权角色'),
            field: 'roleName',
            width: 150,
            editRender: {name: 'input'},
            slots: {
              edit: 'role'
            }
          },
          {
            title: this.$t1('自然省份'),
            field: 'areaName',
            width: 150,
            editRender: {name: 'input'},
            slots: {
              edit: 'area'
            }
          },
          {field: 'treePathName', title: this.$t1('上级机构'), width: 150},
          {field: 'companyName', title: this.$t1('所属组织'), width: 150},
          {field: 'createDate', title: this.$t1('创建时间'), width: 150},
          {field: 'modifyDate', title: this.$t1('更新时间'), width: 150},
          {width: 300, title: '', fixed: 'right', sortable: false, slots: {default: 'operate'}}
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
      });
    },
    openChangeParentDialog(obj) {
      this.changeForm1.sale_org = obj.row;
      this.changeForm1.parent = '';
      this.showChangeParentDialog = true;
    },
    changeRowParent() {
      let that = this;
      this.$baseConfirm(this.$t1('您确定提交修改吗？')).then(() => {
        that.$http({
          url: 'changePage',
          method: `post`,
          data: {id: that.changeForm1.sale_org.id, parentId: this.changeForm1.parent.id || ''},
          isLoading: true,
          callback: res => {
            this.showChangeParentDialog = false;
            if (res.type == 'success') {
              that.searchEvent();
            }
          },
          error: error => {
            this.showChangeParentDialog = false;
          }
        });
      });
    },
    confirmInsertSaleOrg(rows) {
      if (rows.length > 0) {
        let row = rows[0];
        this.changeForm1.parent = row;
      }
    },
    async openSortRowDialog(obj) {
      let url = !obj.row.parent ? USER_PREFIX + '/sale_org/listPage' : USER_PREFIX + '/sale_org/getChildren';
      let data = obj.row.parent ? {id: obj.row.parent} : {};
      let rows = [];
      await this.$http({
        url: url,
        method: `post`,
        data: data,
        isLoading: true,
        success: res => {
          if (obj.row.parent) {
            rows = res.objx || [];
          } else {
            rows = res.objx.records || [];
          }
        }
      });
      this.showSortRowDialog = true;
      this.sortRows = rows;
      this.$nextTick(() => {
        this.initSortTable(rows);
      });
    },
    saveSort() {
    },
    initSortTable(rows) {
      let that = this;
      let tableOption = {
        vue: this,
        tableRef: 'sortTable',
        columns: [
          {
            width: 60,
            slots: {
              default: () => {
                return [
                  <span class="drag-btn">
                    <i class="vxe-icon--menu"/>
                  </span>
                ];
              },
              header: () => {
                return [
                  <vxe-tooltip v-model={this.showHelpTip2} content={this.$t1('按住后可以上下拖动排序！')} enterable>
                    <i
                      class="vxe-icon--question"
                      onClick={() => {
                        this.showHelpTip2 = !this.showHelpTip2;
                      }}
                    />
                  </vxe-tooltip>
                ];
              }
            }
          },
          {
            title: this.$t1('机构名称'),
            field: 'name',
            width: 250
          },
          {
            field: 'sn',
            title: this.$t1('机构编码'),
            width: 250
          }
        ],
        config: {
          height: 'auto',
          maxHeight: '100%'
        }
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.sortTableOption = opts;
      });
      this.$refs.sortTable.loadData(rows);
      this.rowDrop();
    },
    rowDrop() {
      this.$nextTick(() => {
        const sortTable = this.$refs.sortTable;
        this.sortable1 = Sortable.create(sortTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          onEnd: ({newIndex, oldIndex}) => {
            const currRow = this.sortRows.splice(oldIndex, 1)[0];
            this.sortRows.splice(newIndex, 0, currRow);
          }
        });
      });
    },
    openDirectorDialog(row) {
      let tableData = this.$refs['table-m1'].getTableData().tableData;
      let index = tableData.findIndex(item => item._X_ROW_KEY == row._X_ROW_KEY);
      this.operateIndex = index;
      this.showDirectorDialog = true;
    },
    confirmInsertDirector(rows) {
      if (rows.length) {
        let row = rows[0];
        let fullData = this.$refs['table-m1'].getTableData().tableData;
        let item = fullData[this.operateIndex];
        item.directorId = row.id;
        item.directorName = row.nickName;
      }
    },
    openRoleDialog(row) {
      let tableData = this.$refs['table-m1'].getTableData().tableData;
      let index = tableData.findIndex(item => item._X_ROW_KEY == row._X_ROW_KEY);
      this.operateIndex = index;
      this.showRoleDialog = true;
    },
    confirmInsertRole(rows) {
      if (rows.length) {
        let row = rows[0];
        let fullData = this.$refs['table-m1'].getTableData().tableData;
        let item = fullData[this.operateIndex];
        item.roleId = row.id;
        item.roleName = row.name;
      }
    },
    openAreaDialog(row) {
      let tableData = this.$refs['table-m1'].getTableData().tableData;
      let index = tableData.findIndex(item => item._X_ROW_KEY == row._X_ROW_KEY);
      this.operateIndex = index;
      this.showAreaDialog = true;
    },
    confirmAreaDialog(rows) {
      if (rows.length) {
        let row = rows[0];
        let $grid = this.$refs['table-m1'];
        let fullData = $grid.getTableData().tableData;
        let item = fullData[this.operateIndex];
        item.areaId = row.id;
        this.$set(item, "areaName", row.name)
      }
    }
  }
};
</script>
