<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品编号" prop="productCode"  size="small">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入产品编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司编码" prop="companyCode"  size="small">
          <el-select v-model="queryParams.companyCode" clearable class="z-select">
            <el-option
              v-for="(item, index) in companyList"
              :key="item.deptCode"
              :label="item.deptName"
              :value="item.deptCode">
              <span style="float: left">{{ item.deptName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deptCode }}</span>
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item  size="small">
        <el-button type="primary" icon="el-icon-search"   @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"   @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="['sfa:orderProduct: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="['sfa:orderProduct: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="['sfa:orderProduct: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="['sfa:orderProduct:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderProductList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编号" align="center" prop="productCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="公司编码" align="center" prop="companyCode" />
      <el-table-column label="公司名称" align="center" prop="companyName" />
<!--     <el-table-column label="是否有效" align="center" prop="delFlag" width="80">-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag v-if="scope.row.delFlag!=1">有效</el-tag>-->
<!--          <el-tag type="info" v-else>无效</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sfa:orderProduct:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sfa:orderProduct:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col>
            <el-form-item label="产品编号" prop="productCode" size="small">
              <el-input v-model="form.productCode" placeholder="请输入产品编号" />
            </el-form-item>
          </el-col>
          <el-col >
              <el-form-item label="产品名称" prop="productName" size="small">
               <el-input v-model="form.productName" placeholder="请输入产品名称" />
              </el-form-item>
          </el-col>
<!--          <el-col :span="12" >-->
<!--            <el-form-item size="small" :class="['treeselectForm','treeselectForm3','treeselectFormz',{borderRed:!validTree},{isDisabled:formIsDisabled}]" label="所属部门" prop="deptId">-->
<!--              <treeselect-->
<!--                class="treePopup"-->
<!--                v-model="form.deptId"-->
<!--                :multiple="false"-->
<!--                :disable-branch-nodes="true"-->
<!--                value-consists-of="LEAF_PRIORITY"-->
<!--                :options="menuOptions"-->
<!--                :normalizer="normalizer1"-->
<!--                placeholder="选择所属部门"-->
<!--                noOptionsText="暂无数据"-->
<!--                @select="treeselectFnSingle"-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col  >
            <el-form-item label="公司名称" prop="companyCode" size="small">
              <el-select
                v-model="form.companyCode" clearable
                v-el-select-loadmore="loadMore()"
                @visible-change="visibleChange"
                clearable
                @change="changeCompanyCode"
                class="z-select">
                <el-option
                  v-for="(item, index) in resOptions2"
                  :key="item.deptCode"
                  :label="item.deptName"
                  :value="item.deptCode">
                  <span style="float: left">{{ item.deptName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deptCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col>-->
<!--            <el-form-item label="是否有效" prop="delFlag" size="small">-->
<!--              <el-radio-group v-model="form.delFlag">-->
<!--                <el-radio label="0">有效</el-radio>-->
<!--                <el-radio label="2">无效</el-radio>-->
<!--              </el-radio-group>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="small">确 定</el-button>
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrderProduct, getOrderProduct, delOrderProduct, addOrderProduct, updateOrderProduct } from "@/api/sfa/orderProduct";
import {_debounce} from "@/utils/debounce";
import {listDept} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import tree from "@/views/components/sfa/treeselect";
import treeSingle from "@/views/components/sfa/treeselectSingle";
import {listChains,companyList} from "@/api/sfa/chains";

export default {
  name: "OrderProduct",
  components: { Treeselect,tree,treeSingle },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单产品表格数据
      orderProductList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: null,
        productName: null,
        deptId: null,
        companyCode: null,
        companyId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productCode: [
          { required: true, message: "请输入产品编码", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "请输入产品名称", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "请选择所属部门", trigger: "change" }
        ],
        companyCode: [
          { required: true, message: "请选择经销商", trigger: "change" }
        ],
        delFlag: [
          { required: true, message: "是否有效", trigger: "blur" }
        ],
      },
      chainsList2:[],
      rangeNumber2: 10,
      rangeNumber:10,
      validTree:true,
      chainsList:[],
      menuOptions: [],
      formIsDisabled:false,
      companyList:[]
    };
  },
  created() {
    this.getList();
    this.getChainList();
    this.getTreeselect();
    this.getChainList2()
  },
  methods: {
    onInput (){
      this.$forceUpdate();
    },
    getChainList2(){
      companyList().then(response => {
        this.resOptions2 = response.data;
        // this.filterMethod2();
        // if(this.title == '修改门店' || this.title == '门店详情'){
        //   this.rangeNumber2 = response.total;
        //   this.loadMore2();
        // }
      });
    },
    getChainList(){
      companyList().then(response => {
        this.companyList = response.data;
      });
    },
    loadMore() {
      return () => (this.rangeNumber += 5);
    },
    loadMore2() {
      return () => (this.rangeNumber2 += 5);
    },
    changeCompanyCode(val){
      this.onInput()
      this.resOptions2.forEach(item=>{
        if(item.deptCode==val){
          this.form.companyId=item.deptId
          this.form.companyName=item.deptName
          return;
        }
      })
    },
    visibleChange2(flag){
      if(flag){
        this.filterMethod2()
      }
    },
    visibleChange(flag){
      if(flag){
        this.filterMethod()
      }
    },
    filterMethod:_debounce(function(filterVal){
      if(filterVal){
        let filterArr = this.resOptions.filter((item)=>{
          return item.deptName.toLowerCase().includes(filterVal.toLowerCase())||item.deptCode.toLowerCase().includes(filterVal.toLowerCase())
        })
        this.chainsList = filterArr;
      }else{
        this.chainsList = this.resOptions;
      }
    },500),
    filterMethod2:_debounce(function(filterVal){
      if(filterVal){
        let filterArr = this.resOptions2.filter((item)=>{
          return item.deptName.toLowerCase().includes(filterVal.toLowerCase())||item.deptCode.toLowerCase().includes(filterVal.toLowerCase())
        })
        this.chainsList2 = filterArr;
      }else{
        this.chainsList2 = this.resOptions2;
      }
    },500),
    userIdFocus(){
      if(this.queryParams.orgIds == null){
        this.$refs['queryParams'].validate((valid) => {
          if (valid) {
            this.validTree = true;
          }else{
            if(this.queryParams.orgIds==null){
              this.validTree = false;
            }else{
              this.validTree = true;
            }
          }
        })
      }else{
        this.validTree = true;
      }
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listDept().then(response => {
        this.menuOptions = this.handleTree(response.data, "deptId", "parentId");
        if(this.menuOptions.length == 1 && (this.menuOptions[0].children == null || this.menuOptions[0].children == undefined||
          (this.menuOptions[0].children != undefined && this.menuOptions[0].children != null && this.menuOptions[0].children.length == 0))){
          this.form.orgId = this.menuOptions[0].deptId;
        }
      });
    },
    /** 转换菜单数据结构 */
    normalizer1(node) {
      let that = this;
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
        isDisabled:that.isDisabled
      };
    },
    treeselectFnSingle(val){
      if(val.deptId != undefined && val.deptId !='' && val.deptId !=null ){
        this.form.deptId = val.deptId;
        this.$refs.form.clearValidate();
        this.getChainList2();
        this.form.companyCode = "";
        this.form.companyName = "";
      }
    },
    /** 查询订单产品列表 */
    getList() {
      this.loading = true;
      listOrderProduct(this.queryParams).then(response => {
        this.orderProductList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productCode: null,
        productName: null,
        deptId: null,
        delFlag: "0",
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        companyCode: null,
        companyId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderProductId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.formIsDisabled= false;

      this.title = "添加订单产品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.orderProductId || this.ids
      getOrderProduct(id).then(response => {
        this.form = response.data;
        this.formIsDisabled = !row.updatable;
        this.open = true;
        this.title = "修改订单产品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderProductId != null) {
            updateOrderProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrderProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.orderProductId || this.ids;
      this.$modal.confirm('是否确认删除订单产品编号为"' + row.productCode + '"的数据项？').then(function() {
        return delOrderProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sfa/orderProduct/export', {
        ...this.queryParams
      }, `orderProduct_${new Date().getTime()}.xlsx`)
    }
  },
  directives:{
    'el-select-loadmore':(el, binding) => {
      // 获取element-ui定义好的scroll盒子
      const SELECTWRAP_DOM = el.querySelector(".el-select-dropdown .el-select-dropdown__wrap");
      if(SELECTWRAP_DOM){
        SELECTWRAP_DOM.addEventListener("scroll", function () {
          /**
           * scrollHeight 获取元素内容高度(只读)
           * scrollTop 获取或者设置元素的偏移值,
           *  常用于:计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
           * clientHeight 读取元素的可见高度(只读)
           * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
           * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
           */
          const condition = this.scrollHeight - this.scrollTop-20 <= this.clientHeight;
          if (condition) binding.value();
        });
      }
    },
  },
};
</script>
