<template>
  <div ref="list">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="95px" @submit.native.prevent>
      <el-form-item label="代理商名称" prop="brokerName">
        <el-input
          v-model="queryParams.brokerName"
          placeholder="请输入代理商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="chargePerson">
        <el-input
          v-model="queryParams.chargePerson"
          placeholder="请输入负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机构" prop="isInstitution">
        <el-select style="width: 100%;" filterable v-model="queryParams.isInstitution" placeholder="请选择是否机构" clearable>
          <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="staus">
        <el-select style="width: 100%;" filterable v-model="queryParams.staus" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.df_broker_staus" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:broker:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:broker:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:broker:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:broker:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="brokerList" @sort-change="handleSortChange"
              @selection-change="handleSelectionChange" row-key="id" :highlight-current-row="true" @row-click="handleRowClick"
              default-expand-all :height="tableHeight + 300"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="id" align="center" prop="id" sortable='custom'/>-->
<!--      <el-table-column label="" prop="" width="200"/>-->
      <el-table-column label="代理商名称"  prop="brokerName" sortable='custom' min-width="180px" fixed="left"/>
      <!-- <el-table-column label="地址" align="center" prop="brokerAddress" sortable='custom'/> -->
      <!-- <el-table-column label="简介" align="center" prop="brokerDesc" sortable='custom' show-overflow-tooltip/> -->
      <el-table-column label="负责人" align="center" prop="chargePerson" sortable='custom' width="90px"/>
      <el-table-column label="联系电话" align="center" prop="contactPhone" sortable='custom' width="100px"/>
      <el-table-column label="邮箱" align="center" prop="email" sortable='custom' width="100"/>
      <el-table-column label="是否机构" align="center" prop="isInstitution" sortable='custom' width="100px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isInstitution"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="staus" sortable='custom'>
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.staus"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="orderNum" sortable='custom' width="100px"/>
      <!-- <el-table-column label="备注" align="center" prop="remark" sortable='custom' show-overflow-tooltip/> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleRead(scope.row)"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:broker:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:broker:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    <pagination-->
<!--      :total="total"-->
<!--      :pageSizes="[5, 10, 30, 50]"-->
<!--      :page.sync="queryParams.pageNum"-->
<!--      :limit.sync="queryParams.pageSize"-->
<!--      @pagination="getList"-->
<!--    />-->

    <!-- 添加或修改代理商经纪对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="上级代理商" prop="parentId">
              <treeselect v-model="form.parentId" :options="brokerOptions" props="lable" :show-count="true" :defaultExpandLevel="Infinity" :disabled="readonly"
                          placeholder="选择上级代理商" :normalizer="tenantIdnormalizer" />
<!--              <el-select v-model="form.parentId" placeholder="选择上级代理商" style="width: 100%">-->
<!--                <el-option-->
<!--                  v-for="item in brokerOptions"-->
<!--                  :key="item.id"-->
<!--                  :label="item.brokerName"-->
<!--                  :value="item.id"-->
<!--                  v-if="item.id != form.id"-->
<!--                />-->
<!--              </el-select>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理商名称" prop="brokerName">
              <el-input v-model="form.brokerName" placeholder="请输入代理商名称" :disabled="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="地址" prop="brokerAddress">
              <el-input v-model="form.brokerAddress" placeholder="请输入地址" :disabled="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input-number style="width: 100%" v-model="form.orderNum" placeholder="请输入显示顺序" :min="0" :disabled="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="chargePerson">
              <el-input v-model="form.chargePerson" placeholder="请输入负责人" :disabled="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" :disabled="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" :disabled="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否机构" prop="isInstitution">
              <el-select v-model="form.isInstitution" placeholder="请选择状态" style="width: 100%" :disabled="readonly">
                <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label"
                           :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="staus">
              <el-radio-group v-model="form.staus" :disabled="readonly">
                <el-radio
                  v-for="dict in dict.type.df_broker_staus"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="简介" prop="brokerDesc">
              <editor v-model="form.brokerDesc" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!readonly">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  pageListBroker,
  getBroker,
  delBroker,
  addBroker,
  updateBroker,
  listBroker,
  changeBrokerStatus,
  listBrokerByTree
} from "@/api/broker/broker";
import AutoTableHeight from '@/views/broker/AutoTableHeight';
import {changeUserStatus, getUser} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "DfBroker",
  mixins: [AutoTableHeight],
  dicts: ["df_broker_staus","sys_yes_no"],
  components: {Treeselect},
  data() {
    return {
      readonly:false,
      brokerOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理商经纪表格数据
      brokerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        parentId: null,
        brokerName: null,
        brokerAddress: null,
        brokerDesc: null,
        orderNum: null,
        chargePerson: null,
        contactPhone: null,
        email: null,
        isInstitution: null,
        staus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // parentId: [
        //   {required: true, message: "父级id不能为空", trigger: "blur"}
        // ],
        brokerName: [
          {required: true, message: "代理商名称不能为空", trigger: "blur"}
        ],
        // brokerAddress: [
        //   {required: true, message: "地址不能为空", trigger: "blur"}
        // ],
        // brokerDesc: [
        //   {required: true, message: "简介不能为空", trigger: "blur"}
        // ],
        // orderNum: [
        //   {required: true, message: "显示顺序不能为空", trigger: "blur"}
        // ],
        // chargePerson: [
        //   {required: true, message: "负责人不能为空", trigger: "blur"}
        // ],
        // contactPhone: [
        //   {required: true, message: "联系电话不能为空", trigger: "blur"}
        // ],
        // email: [
        //   {required: true, message: "邮箱不能为空", trigger: "blur"}
        // ],
        isInstitution: [
          {required: true, message: "是否机构不能为空", trigger: "blur"}
        ],
        staus: [
          {required: true, message: "状态不能为空", trigger: "blur"}
        ],
        // remark: [
        //   {required: true, message: "备注不能为空", trigger: "blur"}
        // ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    tenantIdnormalizer(node, instanceId) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.brokerName,
        children: node.children
      }
    },
    handleStatusChange(row) {
      let text = row.staus === "0" ? "有效" : "禁用";
      this.$modal.confirm('确认要' + text + '"' + row.brokerName + '"用户吗？').then(function () {
        return changeBrokerStatus(row.id, row.staus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.staus = row.staus === "0" ? "1" : "0";
      });
    },
    // 点击行
    handleRowClick(row) {
      this.$emit('row-click', row);
    },
    /** 查询代理商经纪列表 */
    getList() {
      this.loading = true;
      pageListBroker(this.queryParams).then(response => {
        this.brokerList = this.convertToTreeData(response.rows);
        this.total = response.total;
        this.loading = false;
      }).catch(e => {
        this.loading = false;
      });
      listBrokerByTree().then(response => {
        response.data.unshift({ id: null, brokerName: '无' });
        this.brokerOptions = response.data;
      });
      // listBroker().then(response => {
      //   this.brokerOptions = response.data;
      // })
    },
    convertToTreeData(brokerList) {
      const map = {};
      const treeData = [];
      brokerList.forEach(broker => {
        broker.children = [];
        map[broker.id] = broker;
      });
      brokerList.forEach(broker => {
        if (broker.parentId && map[broker.parentId]) {
          map[broker.parentId].children.push(broker);
        } else {
          treeData.push(broker);
        }
      });
      return treeData;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        brokerName: null,
        brokerAddress: null,
        brokerDesc: null,
        orderNum: null,
        chargePerson: null,
        contactPhone: null,
        email: null,
        isInstitution: null,
        staus: null,
        remark: null,
      };
      this.resetForm("form");
    },
    //排序
    handleSortChange(col) {
      this.$sortBy(col, this.queryParams);
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.names = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.isInstitution = "Y";
      this.form.staus = "0";
      this.readonly = false;
      this.open = true;
      this.title = "添加代理商经纪";
    },
    handleRead(row) {
      this.reset();
      const id = row.id || this.ids;
      getBroker(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.readonly = true;
        this.title = "查看代理商经纪";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBroker(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.readonly = false;
        this.title = "修改代理商经纪";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.form.parentId === this.form.id) {
              this.$modal.msgError("上级部门不能选择自己");
              return false;
            }
            updateBroker(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBroker(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.id || this.names;
      this.$modal.confirm('是否确认删除代理商经纪为"' + names + '"的数据项？').then(function () {
        return delBroker(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('broker/broker/export', {
        ...this.queryParams
      }, `代理商经纪信息数据_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
