<template>
  <div
    id="purchaser_info"
    v-loading="loading"
    element-loading-text="拼命加载中......请稍等"
    style="display: flex"
  >
    <div style="width: 300px">
      <div
        style="
          height: 50px;
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <span>购方分组列表</span>
        <el-button
          style="margin-right: 5px"
          v-on:click="createGroupClass"
          type="primary"
          >新建分组</el-button
        >
      </div>
      <div style="display: flex">
        <el-input
          style="margin-right: 5px"
          placeholder="请输入要查询的分类名称"
          prefix-icon="el-icon-search"
          v-model="className"
          clearable
          v-on:clear="groupClassSearch"
        >
        </el-input>
        <el-button
          v-on:click="groupClassSearch"
          style="margin-right: 5px"
          type="primary"
          >查询</el-button
        >
      </div>
      <div style="margin-top: 5px">
        <el-tree
          :data="groupClassList"
          :props="defaultProps"
          node-key="key"
          default-expand-all
          :default-checked-keys="[0]"
          @node-click="getSelectGroupClass"
          :highlight-current="true"
          style="width: 270px"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="classNameSpan">{{ node.label }}</span>
            <span style="margin-left: 10px" v-if="data.key !== 0">
              <el-button
                type="text"
                size="mini"
                @click="() => editGroupList(data)"
                >编辑</el-button
              >
              <el-button
                type="text"
                size="mini"
                @click="() => deleteGroupClass(node, data)"
                >删除</el-button
              >
            </span>
          </span>
        </el-tree>
      </div>
    </div>
    <div
      style="display: flex; flex: 1; flex-direction: column; margin-left: 10px"
    >
      <div style="margin-bottom: 10px">
        <span style="font-weight: 500; color: #0b0e16">购方信息分类</span>
      </div>
      <div
        style="
          display: flex;
          flex-direction: row;
          margin-bottom: 10px;
          width: 75%;
          justify-content: space-between;
        "
      >
        <div style="display: flex">
          <el-input
            style="margin-right: 5px"
            placeholder="请输入客户名称"
            prefix-icon="el-icon-search"
            v-model="search.customerName"
            clearable
            v-on:clear="handleSearch"
          >
          </el-input>
          <el-button
            style="margin-right: 5px"
            type="primary"
            v-on:click="handleSearch"
            >查询</el-button
          >
        </div>
        <div style="margin-right: 0px">
          <el-button
            style="margin-right: 5px"
            type="primary"
            v-on:click="showCustomerAddDialog"
            >新增</el-button
          >
          <el-button
            style="margin-right: 5px"
            type="primary"
            v-on:click="handleSearchResultDeleteChecked"
            >删除
          </el-button>
          <el-button
            style="margin-right: 5px"
            type="primary"
            v-on:click="moveCustomerClassShow"
            >移动到</el-button
          >
        </div>
      </div>
      <div>
        <el-table
          :height="tableHeight"
          ref="searchResultMultipleTable"
          :data="search.resultList"
          @selection-change="handleSearchResultCheckChange"
          border
          stripe
          style="width: 75%"
        >
          <el-table-column
            type="selection"
            width="40"
            align="center"
          ></el-table-column>
          <el-table-column
            type="index"
            :index="pageIndex"
            align="center"
            label="序号"
            width="45"
          ></el-table-column>
          <el-table-column
            prop="customerName"
            label="购方名称"
            width="180"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="customerEntTaxId"
            label="税号"
            width="180"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="address"
            label="公司地址"
            width="180"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="contactPhone"
            label="电话号码"
            width="120"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="bankName"
            label="开户银行"
            width="150"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="bankAccountNumber"
            label="开户银行账号"
            width="130"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="customerMobile"
            label="手机号码"
            width="120"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="email"
            label="邮箱"
            width="140"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="90">
            <template slot-scope="scope">
              <el-button
                @click="handleShowCustomerModifyDialog(scope.row)"
                type="primary"
                size="small"
                >编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div
        style="
          height: 50px;
          width: 75%;
          display: flex;
          justify-content: flex-end;
          align-items: center;
        "
      >
        <el-pagination
          @size-change="handleSearchResultSizeChange"
          @current-change="handleSearchResultCurrentChange"
          :current-page="search.resultPagination.currentPage"
          :page-sizes="search.resultPagination.pageSizes"
          :page-size="search.resultPagination.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="search.resultPagination.total"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      title="新增购方信息"
      :visible.sync="customerAddData.dialogVisible"
      center
      @close="handleCloseDialog('customerAdd')"
    >
      <customer-form
        ref="customerAdd"
        :inputCustomerInfo="customerAddData.inputCustomerInfo"
      ></customer-form>
      <span slot="footer">
        <el-button
          type="primary"
          @click="handleCustomerModifyOrAddSubmit('customerAdd')"
          >立即添加</el-button
        >
        <el-button @click="customerAddData.dialogVisible = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="编辑购方信息"
      :visible.sync="customerModifyData.dialogVisible"
      center
      @close="handleCloseDialog('customerModify')"
    >
      <customer-form
        ref="customerModify"
        :inputCustomerInfo="customerModifyData.inputCustomerInfo"
      ></customer-form>
      <span slot="footer">
        <el-button
          type="primary"
          @click="handleCustomerModifyOrAddSubmit('customerModify')"
          >立即修改</el-button
        >
        <el-button @click="customerModifyData.dialogVisible = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="客户分类信息"
      :visible.sync="isShowClass"
      width="30%"
      :before-close="groupClassClose"
    >
      <div style="display: flex; justify-content: center; align-items: center">
        <span style="color: red">*</span>
        <span style="width: 90px">分类名称：</span>
        <el-input v-model="groupName" placeholder="请输入分类名称"></el-input>
      </div>
      <div
        style="
          display: flex;
          justify-content: center;
          align-items: center;
          margin-top: 10px;
        "
      >
        <span style="width: 90px">分类描述：</span>
        <el-input
          style="margin-left: 5px"
          type="textarea"
          :rows="2"
          placeholder="请输入分类描述"
          v-model="groupDesc"
        >
        </el-input>
      </div>
      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-button @click="groupClassClose">取 消</el-button>
        <el-button type="primary" v-on:click="saveGroupClass">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="客户分类移动"
      :visible.sync="isShowMoveClass"
      width="30%"
      :before-close="moveClassClose"
    >
      <div style="display: flex; justify-content: center; align-items: center">
        <span><span style="color: red">*</span>分类名称：</span>
        <el-select
          v-model="selectClassName"
          v-on:change="classNameChange"
          placeholder="请选择"
        >
          <el-option
            v-for="item in groupClassList[0].children"
            :key="item.key"
            :label="item.label"
            :value="item.key"
          >
          </el-option>
        </el-select>
      </div>
      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-button @click="moveClassClose">取 消</el-button>
        <el-button type="primary" v-on:click="moveCustomerClass"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  customerSearch,
  customerModifyOrAdd,
  customerDelete,
  getSearchHistory,
} from "@/api/user_config";
import cache from "@/utils/cache";
import { AxiosRequestData } from "@/data/axios_request";
import CustomerForm from "@/pages/config/purchaser/components/customer-form";

export default {
  name: "purchaser_info",
  components: {
    "customer-form": CustomerForm,
  },
  data() {
    return {
      loading: false,
      search: {
        groupId: "",
        groupName: "全部客户信息",
        customerName: "",
        resultList: [],
        resultMultipleSelection: [],
        resultPagination: {
          currentPage: 1,
          pageSizes: [10, 30, 50, 100],
          pageSize: 10,
          total: 0,
        },
      },
      tableHeight: "",
      groupClassList: [
        {
          key: 0,
          label: "全部",
          children: [],
        },
      ],
      token: "",
      className: "",
      entTaxId: "",
      isShowClass: false,
      groupName: "",
      groupDesc: "",
      groupSort: 0,
      groupId: "",
      selectClassItem: {},
      classNumber: 0,
      defaultProps: {
        children: "children",
        label: "label",
      },
      isShowMoveClass: false,
      customerClassList: [],
      selectClassName: "",
      customerAddData: {
        dialogVisible: false,
        inputCustomerInfo: {}, // 绑定后，用于清空上次的输入
      },
      customerModifyData: {
        dialogVisible: false,
        inputCustomerInfo: {}, // 要编辑的企业信息
      },
    };
  },
  created() {
    this.tableHeight = window.innerHeight - 250;
    this.callCustomerSearch(
      this.search.resultPagination.currentPage,
      this.search.resultPagination.pageSize
    );
    let company = JSON.parse(cache.getSession("company"));
    this.entTaxId = company.entTaxId;
    this.token = cache.getToken();
    this.getCommodityClassList(false);
  },
  mounted() {
    this.tableHeight = window.innerHeight - 250;
    window.onresize = () => {
      return (() => {
        this.tableHeight = window.innerHeight - 250;
      })();
    };
  },
  methods: {
    pageIndex(index) {
      let currentPage = this.search.resultPagination.currentPage; // 当前页码，具体看组件取值
      let pageSize = this.search.resultPagination.pageSize; // 每页条数，具体是组件取值
      return index + 1 + (currentPage - 1) * pageSize;
    },
    handleSearch() {
      this.callCustomerSearch(1, this.search.resultPagination.pageSize);
    },
    showCustomerAddDialog() {
      if (!this.groupId) {
        this.$message({
          message: "请先选择分组信息，再点击新增按钮！",
          type: "warning",
        });
        return;
      }
      this.customerAddData.inputCustomerInfo = {};
      this.customerAddData.dialogVisible = true;
    },
    handleShowCustomerModifyDialog(row) {
      this.customerModifyData.inputCustomerInfo = { ...row };
      this.customerModifyData.dialogVisible = true;
    },
    handleCloseDialog(refName) {
      // 取消验证提示
      this.$refs[refName].resetFormFields();
    },
    handleSearchResultCheckChange(val) {
      this.search.resultMultipleSelection = val;
      console.log("选中数据");
      console.log(this.search.resultMultipleSelection);
    },
    handleSearchResultDeleteChecked() {
      let entTaxId = JSON.parse(cache.getSession("company")).entTaxId;
      let originalDelList = this.search.resultMultipleSelection;
      if (originalDelList.length > 0) {
        let delList = new Array();
        for (let index = 0; index < originalDelList.length; index++) {
          const element = originalDelList[index];
          delList[index] = {
            customerId: element.customerId,
            customerCode: element.customerCode,
            entTaxId: entTaxId,
          };
        }
        customerDelete(delList)
          .then((val) => {
            this.callCustomerSearch(
              this.search.resultPagination.currentPage,
              this.search.resultPagination.pageSize
            );
            this.$message.success(val.msg);
          })
          .catch((error) => {
            this.$message.error(error);
          });
      } else {
        this.$message({
          message: "请选择需要删除的客户信息！",
          type: "warning",
        });
      }
    },
    handleSearchResultSizeChange(val) {
      this.callCustomerSearch(1, val);
    },
    handleSearchResultCurrentChange(val) {
      this.callCustomerSearch(val, this.search.resultPagination.pageSize);
    },
    handleCustomerModifyOrAddSubmit(refName) {
      console.log("客户修改和添加 参数：" + refName);
      this.$refs[refName]
        .getCustomerInfo()
        .then((val) => {
          let args = {
            customerId: val.customerId,
            customerType: val.customerType,
            customerName: val.customerName,
            customerMobile: val.customerMobile,
            email: val.email,
            groupId: this.groupId,
          };
          if (args.customerType == 2) {
            // 企业客户
            args.customerEntTaxId = val.customerEntTaxId;
            args.address = val.address;
            args.bankName = val.bankName;
            args.bankAccountNumber = val.bankAccountNumber;
            args.contactPhone = val.contactPhone;
          }
          customerModifyOrAdd(args)
            .then((val) => {
              // 成功关闭弹窗
              this.customerAddData.dialogVisible = false;
              this.customerModifyData.dialogVisible = false;
              this.callCustomerSearch(1, this.search.resultPagination.pageSize);
              this.$message.success(val.msg);
            })
            .catch((err) => {
              this.$message.error(err);
            });
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    /**
     * 客户搜索
     * @param {Number} pageNum : 当前页码
     * @param {Number} pageSize : 每页数量
     */
    callCustomerSearch(pageNum, pageSize) {
      customerSearch({
        groupId: this.groupId,
        customerName: this.search.customerName,
        pageNum: pageNum,
        pageSize: pageSize,
      })
        .then((val) => {
          this.search.resultPagination.total = val.data.total;
          this.search.resultPagination.pageSize = val.data.size;
          this.search.resultPagination.currentPage = val.data.current;
          this.search.resultList = val.data.records;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    // 获取商品分类列表
    async getCommodityClassList(status) {
      const url = "/sys/customer/group/findPage";
      if (this.token) {
        this.loading = true;
        let response = await AxiosRequestData(
          url,
          this.token,
          {
            groupName: this.className,
            entTaxId: this.entTaxId,
            pageNum: 1,
            pageSize: 1000,
          },
          false,
          2
        );
        if (response) {
          if (response.code === 0) {
            this.loading = false;
            this.classNumber = response.data.total + 2;
            let groupList = [];
            let group = {};
            // if (!status) {
            //   group = {
            //     key: 0,
            //     name: '全部',
            //     desc: '全部',
            //     sort: 0
            //   }
            //   groupList = groupList.concat(group)
            // }
            response.data.records.forEach((item, index) => {
              group = {
                key: item.groupId,
                label: item.groupName,
                desc: item.groupDesc,
                sort: item.sort,
              };
              groupList = groupList.concat(group);
            });
            this.groupClassList[0].children = groupList;
            // this.$refs.classTable.setCurrentRow(this.groupClassList[0])
          } else {
            this.loading = false;
          }
        }
      }
    },
    // 获取选中分类的数据
    getSelectGroupClass(row) {
      this.selectClassItem = row;
      if (row.key === 0) {
        this.groupId = "";
      } else {
        this.groupId = row.key;
      }
      this.callCustomerSearch(1, 10);
    },
    // 分类数据查询
    groupClassSearch() {
      if (this.className) {
        this.getCommodityClassList(true);
      } else {
        this.getCommodityClassList(false);
      }
    },
    // 新增分类数据页面显示
    createGroupClass() {
      this.isShowClass = true;
    },
    // 编辑分类信息页面显示
    editGroupList(row) {
      this.isShowClass = true;
      this.groupName = row.label;
      this.groupDesc = row.desc;
      this.groupId = row.key;
      this.groupSort = row.sort;
      this.classNumber = row.sort;
    },
    // 分类页面弹框关闭后调用
    groupClassClose() {
      this.isShowClass = false;
      this.groupName = "";
      this.groupDesc = "";
      this.groupId = "";
      this.groupSort = 0;
      this.classNumber = 0;
    },
    // 保存分类信息
    async saveGroupClass() {
      if (!this.groupName) {
        this.$message({
          message: "分类名称不允许为空！",
          type: "warning",
        });
        return null;
      }
      const url = "/sys/customer/group/save";
      if (this.token) {
        this.loading = true;
        let response = await AxiosRequestData(
          url,
          this.token,
          {
            groupId: this.groupId,
            groupName: this.groupName,
            groupDesc: this.groupDesc,
            sort: this.classNumber,
            entTaxId: this.entTaxId,
            reqChannel: 4,
          },
          false,
          1
        );
        if (response) {
          if (response.code === 0) {
            this.loading = false;
            this.isShowClass = false;
            this.$message({
              message: "保存成功！",
              type: "success",
            });
            this.groupName = "";
            this.groupDesc = "";
            await this.getCommodityClassList(false);
          } else {
            this.loading = false;
            this.$message.error(response.msg);
          }
        }
      }
    },
    // 删除分类信息
    async deleteGroupClass(row) {
      this.$confirm("确认删除当前分类名称吗？")
        .then(async (_) => {
          // done()
          const url = "/sys/customer/group/delete";
          if (this.token) {
            this.loading = true;
            let response = await AxiosRequestData(
              url,
              this.token,
              {
                delList: [row.key],
              },
              false,
              1
            );
            if (response) {
              if (response.code === 0) {
                this.loading = false;
                this.$message({
                  message: "删除成功！",
                  type: "success",
                });
                await this.getCommodityClassList(false);
              } else {
                this.loading = false;
                this.$message.error(response.msg);
              }
            }
          }
        })
        .catch((_) => {});
    },
    // 移动商品分类页面显示
    moveCustomerClassShow() {
      let originalDelList = this.search.resultMultipleSelection;
      if (originalDelList && originalDelList.length > 0) {
        this.isShowMoveClass = true;
        let customerList = [];
        originalDelList.forEach((item, index) => {
          let customer = {
            customerId: item.customerId,
            groupId: "",
          };
          customerList = customerList.concat(customer);
        });
        this.customerClassList = customerList;
        this.handleSearch();
      } else {
        this.$message({
          message: "请选择需要移动的商品信息",
          type: "warning",
        });
      }
    },
    // 移动客户分类
    async moveCustomerClass() {
      if (this.selectClassName) {
        this.customerClassList.forEach((item, index) => {
          item.groupId = this.selectClassName;
        });
        const url = "/sys/customer/changeGroup";
        if (this.token) {
          this.loading = true;
          let response = await AxiosRequestData(
            url,
            this.token,
            this.customerClassList,
            false,
            1
          );
          if (response) {
            if (response.code === 0) {
              this.loading = false;
              this.isShowMoveClass = false;
              this.$message({
                message: "移动成功！",
                type: "success",
              });
            } else {
              this.loading = false;
              this.$message.error("移动失败");
            }
          }
        }
      } else {
        this.$message({
          message: "请选择分类信息！",
          type: "warning",
        });
      }
    },
    // 关闭移动分类页面
    moveClassClose() {
      this.isShowMoveClass = false;
    },
    // 分类名称选择
    classNameChange(data) {
      this.selectClassName = data;
    },
  },
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.classNameSpan {
  width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
}
</style>
