<template>
  <div id="containt">
    <el-tabs v-model="activeName" class="tab-box">
      <el-tab-pane :label="$t1('常规')" name="first">
        <editView
          v-if="showEdit"
          visible-key="showEdit"
          :_dataId.sync="dataId"
          :parent-target="_self"
          @reload="$reloadHandle"
          :userType="userType"
          :flag="flag"
        ></editView>
      </el-tab-pane>
      <el-tab-pane :label="$t1('列表')" name="second">
        <div class="tree-box fl">
          <div class="tit" @click="clearNodeClick">
            <b>{{ $t1("机构分类") }}</b>
          </div>
          <el-tree
            :props="defaultProps"
            :load="loadNode"
            node-key="id"
            ref="tree"
            highlight-current
            lazy
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            class="tree-list"
            icon-class="el-icon-arrow-down"
          ></el-tree>
        </div>
        <label id="labBtn">
          <div class="icon">
            <i class="el-icon-more"></i>
            <i class="el-icon-more"></i>
          </div>
        </label>
        <div class="main-right fr" style="padding-left: 6px">
          <div class="grid-height">
            <vxe-grid
              id="table-m1"
              ref="table-m1"
              :auto-resize="true"
              v-bind="vxeOption"
              @resizable-change="$vxeTableUtil.onColumnWitchChange"
              @custom="$vxeTableUtil.customHandle"
            >
              <template #form>
                <tableForm
                  :formData.sync="formData"
                  :advancedFormData.sync="advancedFormData"
                  @searchEvent="searchEvent"
                  @resetEvent="resetEvent"
                >
                  <template #buttonLeft>
                    <vxe-button
                      status="primary"
                      class="button-sty"
                      icon="el-icon-plus"
                      @click="openEditDialog"
                    >
                      {{ $t1("新增") }}
                    </vxe-button>
                    <base-table-export
                      :option="{ title: $t1('账户导出'), targetRef: 'table-m1' }"
                      :parent-target="_self"
                    />
                    <vxe-button
                      status="primary"
                      class="button-sty"
                      icon="el-icon-download"
                      @click="importExcel"
                    >
                      {{ $t1("导入") }}
                    </vxe-button>
                    <base-input-export :option="exportOption" :parent-target="_self" />
                  </template>
                  <template #buttonRight>
                    <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>
                  </template>
                </tableForm>
              </template>
            </vxe-grid>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import editView from "./form_edit.vue";
import { treeScollx } from "@base/utils/global.js";
import tableForm from "@base/components/table/tableForm";

export default {
  name: "user:form_list",
  props: {
    userType: {
      type: Number,
    },
    flag: String,
  },
  components: {
    tableForm,
    editView: () => import("./edit.vue"),
  },
  created() {},
  activated() {
    // this.initTableList();
  },
  async mounted() {
    treeScollx({ target: this, type: "default" });
    await this.initOutUserRoleCode();
    this.getRoleList();
    this.initTableList();
  },
  data() {
    return {
      exportOption: {
        prefix: USER_PREFIX,
        tableRef: "table-m1",
        title: this.$t1("用户"),
        codes: [
          "USEREXCEL",
          "USERPDF",
          "USERPRINT",
          "USERHIPRINT",
          "USERJDPRINT",
          "USERPDDPRINT",
          "USERVIPPRINT",
        ],
        onBeforePrint: (done, { etCode, etType }) => {
          /*etType: 2 菜鸟打印,3 网页打印,6 京东打印*/
          done();
        },
        onAfterPrint: ({ etCode, etType }, close) => {
          /*etType: 2 菜鸟打印,3 网页打印,6 京东打印*/
          /*close();//关闭弹框*/
        },
      },
      printOption: {
        prefix: USER_PREFIX,
        tableRef: "table-m1",
        param: {
          type: "print",
          code: "USERPRINT",
          param: "tableDefault",
        },
      },
      showEdit: false,
      activeName: "second",
      showUpload: true,
      uploadSize: 10,
      value10: "",
      dataId: "",
      tp: false,
      showUserDialog: false,
      nickName: "dd",
      formData: { saleOrgName: null, roleCodes: [] },
      vxeOption: {
        className: "list-table",
      },
      defaultProps: {
        label: "name", //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: "leaf",
      },
      showAdvancedSearch: false,
      advancedFormData: {},
      roleList: [],
      distributorCode: "distributor",
      outUserCodes: [],
    };
  },
  methods: {
    searchEvent() {
      this.$refs["table-m1"].commitProxy("reload");
    },
    resetEvent() {
      this.formData = {};
      this.advancedFormData = {};
      this.$refs.tree.setCurrentKey();
      this.$refs["table-m1"].commitProxy("reload");
    },
    openEditDialog(id) {
      this.dataId = !id || typeof id == "object" ? 0 : id;
      this.activeName = "first";
      this.$openEditView("showEdit");
    },
    clearNodeClick() {
      this.formData.saleOrgId = "";
      this.formData.saleOrgName = "";
      this.$refs.tree.setCurrentKey();
      this.searchEvent();
    },
    handleNodeClick(data, node, v) {
      this.$set(this.formData, "saleOrgId", data.id);
      this.$set(this.formData, "saleOrgName", data.name);
      this.$forceUpdate();
      this.searchEvent();
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      let id = node && node.data && node.data.id ? node.data.id || "" : "";
      let param = { enabled: true };
      let url = !id
        ? USER_PREFIX + "/sale_org/getAllList"
        : USER_PREFIX + "/sale_org/getChildren";
      this.$http({
        url: url,
        method: "post",
        data: {
          parent: id,
          enabled: true,
        },
        success: (res) => {
          let rows = res.objx || [];
          if (rows.length) {
            rows.forEach((value) => {
              value.leaf = !value.hasChild;
            });
            if (node.level === 0) {
              if (rows[0].isParent) {
                if (node.childNodes && node.childNodes.length) {
                  this.$nextTick(() => {
                    let nodedata = node.childNodes[0];
                    nodedata.expanded = true;
                    nodedata.loadData();
                  });
                }
              }
            }
          }
          resolve(rows);
        },
      });
    },
    initTableList() {
      let otherColumns = [];
      let userType = this.userType;
      if (userType == 1) {
      } else if (userType == 2) {
        otherColumns.push(
          ...[
            {
              field: "signatoryName",
              title: this.$t1("签约人"),
              width: 150,
            },
            {
              field: "signatoryMobile",
              title: this.$t1("签约人电话"),
              width: 150,
            },
          ]
        );
      }
      let tableOption = {
        vue: this,
        tableRef: "table-m1",
        tableName: "basic_user_list-m11",
        path: USER_PREFIX + "/user/listAllPage",
        param: () => {
          let formData = {
            ...this.formData,
            ...this.advancedFormData,
          };
          let outUserCodes = this.outUserCodes;
          if (this.userType == 1) {
            //组织用户
            formData.neRoleCodes = [...outUserCodes];
          } else if (this.userType == 2) {
            //外部用户
            if (!formData.roleCodes || !formData.roleCodes.length) {
              formData.roleCodes = [...outUserCodes];
            }
          }
          return formData;
        },
        columns: [
          {
            type: "checkbox",
            width: 48,
            resizable: false,
            fixed: "left",
          },
          {
            title: this.$t1("登录名"),
            field: "loginAccount",
            width: 250,
            fixed: "left",
          },
          {
            field: "nickName",
            title: this.$t1("姓名"),
            width: 150,
          },
          {
            field: "mobile",
            title: this.$t1("手机号"),
            width: 150,
          },
          {
            width: 150,
            title: this.$t1("头像"),
            field: "headPhotoUrl",
            sortable: false,
            slots: {
              default: ({ row, rowIndex }) => {
                let option = {
                  title: this.$t1("头像"),
                  rows: row.headPhotoUrl,
                  showViewButton: false,
                };
                return [<base-attachment option={option} />];
              },
            },
          },
          {
            field: "enabled",
            title: this.$t1("是否启用"),
            width: 150,
            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>];
                }
              },
            },
          },
          {
            field: "roleNames",
            title: this.$t1("角色"),
            width: 150,
          },
          {
            field: "saleOrgNames",
            title: this.$t1("机构"),
            width: 150,
          },
          {
            field: "positionNames",
            title: this.$t1("岗位"),
            width: 150,
          },
          {
            field: "birth",
            title: this.$t1("出生日期"),
            width: 150,
            slots: {
              default: ({ row }) => {
                var val = row.birth;
                if (val) {
                  return val.substring(0, 10);
                }
              },
            },
          },
          {
            field: "zipCode",
            title: this.$t1("邮编"),
            width: 150,
          },
          {
            field: "address",
            title: this.$t1("地址"),
            width: 150,
          },
          {
            field: "empNo",
            title: this.$t1("员工编码"),
            width: 150,
          },
          {
            field: "gender",
            title: this.$t1("性别"),
            width: 150,
            slots: {
              default: ({ row }) => {
                var val = row.gender;
                if (val == 1) {
                  return this.$t1("男");
                } else if (val == 2) {
                  return this.$t1("女");
                }
              },
            },
          },
          {
            field: "companyNames",
            title: this.$t1("所属组织"),
            width: 250,
          },
          ...otherColumns,
          {
            field: "createBy",
            title: this.$t1("创建人"),
            width: 150,
          },
          {
            field: "modifyBy",
            title: this.$t1("更新人"),
            width: 150,
          },
          {
            field: "modifyDate",
            title: this.$t1("更新时间"),
            width: 150,
          },
          {
            field: "createDate",
            title: this.$t1("创建时间"),
            width: 150,
          },
          {
            width: 47,
            fixed: "right",
            title: "",
            sortable: false,
            slots: {
              default: ({ row }) => {
                return [
                  <a
                    href="javascript:void(0);"
                    class="a-link"
                    onclick={() => {
                      this.openEditDialog(row.id);
                    }}
                  >
                    <el-tooltip
                      enterable={false}
                      enterable={false}
                      effect="dark"
                      content={this.$t1("查看")}
                      placement="top"
                      popper-class="tooltip-skin"
                    >
                      <i class="el-icon-edit" />
                    </el-tooltip>
                  </a>,
                ];
              },
            },
          },
        ],
        searchColumns: [
          {
            title: this.$t1("机构名称"),
            field: "saleOrgName",
            type: "input",
            common: true,
            disabled: true,
            defaultValueEnabled: false,
          },
          {
            title: this.$t1("登录名"),
            field: "loginAccount",
            type: "input",
            common: true,
          },
          { title: this.$t1("姓名"), field: "nickName", type: "input", common: true },
          { title: this.$t1("手机号"), field: "mobile", type: "input", common: true },
          {
            title: this.$t1("角色"),
            field: "roleCodes",
            type: "select",
            common: true,
            itemOption: [],
            multiple: true,
            syncHandle: () => {
              return this.getRoleList2();
            },
          },
          /*{
            title: "词汇", field: "dictSn", type: "select", common: true, itemOption: [], syncHandle: () => {
              return this.getDict()
            }
          },*/
          {
            title: this.$t1("登录名(批量)"),
            field: "loginAccounts",
            type: "inputBatch",
            common: false,
          },
          {
            title: this.$t1("性别"),
            field: "gender",
            type: "select",
            common: false,
            itemOption: [
              { label: this.$t1("男"), value: 1 },
              { label: this.$t1("女"), value: 2 },
            ],
          },
          { title: this.$t1("邮编"), field: "zipCode", type: "input", common: false },
          {
            title: this.$t1("是否启用"),
            field: "enabled",
            type: "select",
            common: false,
            itemOption: [
              { label: this.$t1("启用"), value: true },
              { label: this.$t1("禁用"), value: false },
            ],
          } /*,
          {title: this.$t1('客户名称'), field: "customerName", type: "input", common: true, slot: "customerName"},
          {
            title: this.$t1('日期'),
            field: "startDate",
            field2: "endDate",
            type: "dateRange",
            common: true,
            widgetType: "date",
            valueFormat: "yyyy-MM-dd"
          },
          {title: this.$t1('年份'), field: "year", type: "date", common: true, widgetType: "year", valueFormat: "yyyy"},*/,
        ],
        config: {
          pagerConfig: {
            pageSize: 500,
          },
        },
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then((opts) => {
        this.vxeOption = opts;
      });
      /* this.$nextTick(() => {
        this.$refs['baseBillExport'].initExportData({
          target: this,
          btn: [{ code: 'USEREXCEL', name: '导出Excel(按模版)', type: 0 }, { code: 'USERPDF', name: '导出Pdf(按模版)', type: 1 }, { code: 'USERPRINT', name: '菜鸟打印', type: 2 }],
          param: item => {
            let checkRows = this.$refs['table-m1'].getCheckboxRecords(true);
            if (item.type != 2) {
              return checkRows.map(row => {
                return { id: row.id };
              });
            } else {
              let rows = checkRows.map(row => row.id);
              return rows.length ? { id: rows } : null;
            }
          }
        });
      }); */
    },
    importExcel() {
      let that = this;
      that.$excelImport({
        prefix: USER_PREFIX,
        excel: USER_PREFIX + "/excelTemplate/user/user.xlsx",
        multi: true,
        saveUrl: USER_PREFIX + "/user/batchImport",
        callback: () => {
          that.searchEvent();
        },
      });
    },
    getRoleList2() {
      return new Promise((resolve, reject) => {
        this.$http({
          url: USER_PREFIX + "/role/list",
          method: "post",
          success: (res) => {
            let rows = res.objx || [];
            let outUserCodes = this.outUserCodes;
            if (this.userType == 1) {
              //组织用户
              rows = rows.filter((row) => !outUserCodes.includes(row.code));
            } else if (this.userType == 2) {
              //外部用户
              rows = rows.filter((row) => outUserCodes.includes(row.code));
            }
            let result = rows.map((row) => {
              return {
                value: row.code,
                label: row.name,
              };
            });
            resolve(result);
          },
        });
      });
    },
    getDict() {
      return new Promise((resolve, reject) => {
        this.$getBaseDicts({
          code: "orderType",
          success: ({ dicts, dictMap }) => {
            let result = dicts.map((row) => {
              return {
                value: row.sn,
                label: row.value,
              };
            });
            resolve(result);
          },
        });
      });
    },
    getRoleList() {
      return this.$http({
        url: USER_PREFIX + "/role/list",
        method: "post",
        success: (res) => {
          let rows = res.objx || [];
          let outUserCodes = this.outUserCodes;
          if (this.userType == 1) {
            //组织用户
            rows = rows.filter((row) => !outUserCodes.includes(row.code));
          } else if (this.userType == 2) {
            //外部用户
            rows = rows.filter((row) => outUserCodes.includes(row.code));
          }
          this.roleList = rows;
          return rows;
        },
      });
    },
    async initOutUserRoleCode() {
      return this.$http({
        url: USER_PREFIX + "/system_parameter/getByCode",
        method: "post",
        data: { code: "outUserRoleCode" },
        success: (res) => {
          let value = !res.objx || !res.objx.value ? "distributor" : res.objx.value;
          let codes = value.split(",");
          this.outUserCodes = codes;
        },
      });
    },
  },
};
</script>
