<template>
  <div>
    <el-card>
      <el-row type="flex">
      <el-col style="flex: 1" v-show="Dictionary">
        <el-col v-if="showSearch" style="min-width: 300px; max-width: 100%">
          <el-tree
            :data="treeList"
            class="tree"
            :default-expand-all="true"
            @node-click="handleNodeClick"
            :expand-on-click-node="false"
            highlight-current
          >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span style="font-size: 14px; font-weight: 500">{{
                    node.label
                  }}</span>
                  <el-button
                    type="text"
                    size="mini"
                    style="margin-left: 10px"
                    :disabled="data.parentCode != null"
                    @click="() => append(data,'add')">
                  新增
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  :disabled="data.parentCode == null"
                  @click="() => append(data, 'edit')">
            编辑
          </el-button>
          <el-button
            type="text"
            size="mini"
            :disabled="data.parentCode == null"
            @click="delTree(data)">
            删除
          </el-button>

              </span
              >
          </el-tree>
        </el-col>
      </el-col>
        <el-button
          type="success"
          @click="Dictionary = !Dictionary"
          icon="el-icon-arrow-left"
          v-show="Dictionary"
          class="iconButton"
        >
        </el-button>
        <el-button
          type="success"
          @click="Dictionary = !Dictionary"
          icon="el-icon-arrow-right"
          v-show="!Dictionary"
          class="iconButton"
        >
        </el-button>
      <el-col style="border-left: 3px solid #dddddd; overflow-y: hidden">
      <el-form :model="query" label-width="auto" v-show="showSearch" size="mini" class="order-el-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="当前仓库:" class="query-form-item">
              <invSelect :value.sync="query.invCode" :params.sync="filterBadInv" :changeValue.sync="invChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="编码/名称:" class="query-form-item">
              <el-input v-model="query.key" placeholder="请输入编号/采集点名称" clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="top-right-btn">
        <el-button-group>
          <el-button icon="el-icon-view" type="primary" @click="hideSearch">显示/隐藏搜索栏</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="addCollectionPoints">新增采集点</el-button>
        </el-button-group>
      </div>
        <el-divider style="margin: 15px"></el-divider>
      <el-table v-loading="loading" :data="list" style="width: 100%" :row-style="{height: '32px' }"  @current-change="handCurrentChange" highlight-current-row
      >
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="采集点编号" prop="code"></el-table-column>
        <el-table-column label="采集点名称" prop="name"></el-table-column>
        <!--<el-table-column label="采集点负责人" prop="employeeName"></el-table-column>-->
        <el-table-column label="单据类型" prop="busType"></el-table-column>
        <el-table-column label="扫码方式" prop="scanType">
          <template slot-scope="scope">
            {{ scanTypeEnum[scope.row.scanType].desc }}
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark"></el-table-column>
        <el-table-column label="操作" fixed="right" width="100">
          <template slot-scope="scope">
            <!--<el-button-->
            <!--  type="text"-->
            <!--  size="small"-->
            <!--  @click.native.stop="printLabel(scope.row)"-->
            <!--&gt;打印-->
            <!--</el-button>-->
            <el-button
              type="text"
              size="small"
              @click.native.stop="editCollectionPoints(scope.row)"
            >编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click.native.stop="deleteCollectionPoints(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      </el-col>
      </el-row>
    </el-card>
    <el-dialog
      :title="fromMap[fromName]"
      :visible.sync="addCollectionPointsDialogVisible"
      width="40%"
      v-if="addCollectionPointsDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="formData" style="width: 80%;" ref="dataForm" :rules="formRules"
               label-width="auto"
      >
        <el-row :gutter="20" class="el-row">
          <el-col :span="24" class="el-col">
            <el-form-item label="采集点编号:" prop="code" class="query-form-item">
              <el-input
                v-model="formData.code" style="width: 80%"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="el-col">
            <el-form-item label="采集点名称:" prop="name" class="query-form-item">
              <el-input
                v-model="formData.name" style="width: 80%"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="el-col">
            <el-form-item label="所属仓库:" prop="busType" class="query-form-item">
              <el-select v-model="formData.invCode" placeholder="请选择所属仓库"
                         style="width: 80%"
                         clearable
                         @change="handleInvChange"
              >
                <el-option
                  v-for="item in invList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--<el-col :span="24" class="el-col">-->
          <!--  <el-form-item label="采集点负责人:" prop="chargeUser" class="query-form-item">-->
          <!--    <el-select v-model="formData.chargeUser" placeholder="请选择所属仓库"-->
          <!--               style="width: 80%"-->
          <!--               clearable-->
          <!--    >-->
          <!--      <el-option-->
          <!--        v-for="item in users"-->
          <!--        :key="item.id"-->
          <!--        :label="item.employeeName"-->
          <!--        :value="item.id">-->
          <!--        <span style="float: left">{{ item.employeeName }}</span>-->
          <!--      </el-option>-->
          <!--    </el-select>-->
          <!--    &lt;!&ndash;<el-input&ndash;&gt;-->
          <!--    &lt;!&ndash;  v-model="formData.chargeUser" style="width: 80%"&ndash;&gt;-->
          <!--    &lt;!&ndash;  auto-complete="off"&ndash;&gt;-->
          <!--    &lt;!&ndash;&gt;</el-input>&ndash;&gt;-->
          <!--  </el-form-item>-->
          <!--</el-col>-->

          <!--<el-col :span="24" class="el-col">-->
          <!--  <el-form-item label="所属仓库:" prop="invCode" class="query-form-item">-->
          <!--    <invSelect :value.sync="formData.invCode" :params.sync="filterBadInv" @change="handleInvChange"-->
          <!--               style="width: 80%"-->
          <!--    />-->
          <!--  </el-form-item>-->
          <!--</el-col>-->
          <el-col :span="24" class="el-col">
            <el-form-item label="单据类型:" prop="busType" class="query-form-item">
              <el-select v-model="formData.busType" placeholder="请选择单据类型"
                         style="width: 80%"
                         clearable
              >
                <el-option
                  v-for="item in busTypes"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24" class="el-col">
            <el-form-item label="扫码方式:" prop="scanType" class="query-form-item">
              <el-select v-model="formData.scanType" style="width: 80%" placeholder="选择扫码方式" clearable>
                <el-option label="三期校验" :value="1"></el-option>
                <el-option label="无三期校验" :value="2"></el-option>
                <el-option label="扫码结果" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24" class="el-col">
            <el-form-item label="备注:" prop="remark" class="query-form-item">
              <el-input
                v-model="formData.remark" style="width: 80%"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="hideForm">取消</el-button>
        <el-button
          type="primary"
          @click.native="formSubmit()"
        >提交
        </el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :title="formMap[formName]"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="subFormVisible"
      width="60%"
      top="5vh"
    >
      <el-form :model="subData" ref="dataForm"  label-width="80px">
        <el-row :gutter="20" class="el-row" type="flex">
          <el-col :span="12" class="el-col">
            <el-form-item label="上级菜单" prop="parentCode">
                <el-select v-model="subData.parentCode" placeholder="选择上级菜单"
                           style="width: 80%"
                           clearable
                           disabled
                >
                  <el-option
                    v-for="item in fromDeptOptions"
                    :key="item.parentCode"
                    :label="item.parentName"
                    :value="item.parentCode">
                    <span style="float: left">{{ item.parentName }}</span>
                  </el-option>
                </el-select>

            </el-form-item>
          </el-col>
          <el-col :span="12" class="el-col">
            <el-form-item label="名称" prop="name" class="query-form-item">
              <el-input
                v-model="subData.name" style="width: 80%"
                placeholder="请输入名称"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="el-row" type="flex">
          <el-col class="el-col">
            <el-form-item label="备注:" prop="remark" class="query-form-item">
              <el-input
                v-model="subData.remark"
                type="textarea"
                style="width: 90%"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="hideForm">取消</el-button>
        <el-button
          type="primary"
          @click.native="forInvSubmit()"
          :loading="subLoading"
        >提交
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCollectPoints,
  addCollectPoint,
  updateCollectPoint,
  delCollectPoint,
  getUsers, getTree, addTree, deleteTree
} from '@/api/basic/collectPoint/collectPointManage'
import { getBusTypeList, getLocalJoinByUser } from '@/api/basic/busType'
import {getCollectBusType} from "@/api/basic/collectPoint/gatherOrderType"
import { getInvListByUser } from '@/api/system/invWarehouse'


export default {

  data() {
    return {
      query: {
        invCode: this.$store.getters.locInvCode,
        page: 1,
        limit: 10
      },
      showSearch: true,
      Dictionary: true,
      filterBadInv: true,
      loading: false,
      list: [],
      fromName: 'add',
      fromMap: {
        'add': '新增采集点',
        'edit': '编辑采集点'
      },
      formName: 'add',
      formMap: {
        add: "新增",
        edit: "编辑"
      },
      addCollectionPointsDialogVisible: false,
      adduserDialogVisible: false,
      subFormVisible: false,
      fromDeptOptions: [],
      subData: {},
      formData: {},
      total: 0,
      busTypes: [],
      invList: [],
      users: [],
      formRules: {
        code: [
          { required: true, message: '请输入采集点编号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入采集点名称', trigger: 'blur' }
        ],
        busType: [
          { required: true, message: '请选择单据类型', trigger: 'blur' }
        ]
      },
      scanTypeEnum: {
        1: { key: 1, desc: '三期校验' },
        2: { key: 2, desc: '无三期校验' },
        3: { key: 3, desc: '扫码结果' }
      },
      invQuery : {
        code : ''
      },
      currentRow: {
        name: "采集点",
        code: null
      },
      userQuery: {},
      treeList:[]
    }
  },
  methods: {
    hideSearch() {
      this.showSearch = !this.showSearch
    },
    onReset() {
      this.$router.push({
        path: ''
      })
      this.query = {
        page: 1,
        limit: 10,
        invCode: this.$store.getters.locInvCode
      }
      this.getList()
    },
    onSubmit() {
      this.query.page = 1
      this.getList()
    },
    addCollectionPoints() {
      this.formData = {}
      this.fromName = 'add'
      this.addCollectionPointsDialogVisible = true
    },
    getList() {
      this.loading = true
      getCollectPoints(this.query).then((response) => {
        if (response.code == 20000) {
          this.list = response.data.list || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.message)
        }
        this.loading = false
      })
        .catch(() => {
          this.loading = false
          this.list = []
          this.total = 0
        })
    },
    getBusType() {
      let query = {
        page: 1,
        limit: 10
      }
      getCollectBusType(query)
        .then((response) => {
          this.busTypes = response.data.list || []
          // this.filterQuery.action = this.busTypes[0].action;
          // this.getList();
        })
        .catch(() => {
        })
    },
    getInvList() {
      let query = {
        advanceType: 1,
      };
      getInvListByUser(query)
        .then((response) => {
          this.invList = response.data || [];
        })
        .catch(() => {
        });
    },
    hideForm() {
      this.addCollectionPointsDialogVisible = false
      this.subFormVisible = false
    },
    formSubmit() {
      if (this.fromName == 'add') {
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) {
            return this.$message.error('请完善采集点信息!')
          }
          addCollectPoint(this.formData).then(res => {
            if (res.code == 20000) {
              this.$message.success('新增成功')
              this.addCollectionPointsDialogVisible = false
              this.getList()
            } else {
              this.$message.error('新增失败')
            }
          }).catch(() => {
          })
        })
      } else {
        updateCollectPoint(this.formData).then(res => {
          if (res.code == 20000) {
            this.$message.success('更新成功')
            this.addCollectionPointsDialogVisible = false
            this.getList()
          } else {
            this.$message.error('更新失败')
          }
        })
      }
    },
    editCollectionPoints(row) {
      this.fromName = 'edit'
      this.formData = row
      // const user = this.users.find(user => user.id === row.chargeUser);
      this.handleInvChange(row.invCode)
      this.addCollectionPointsDialogVisible = true
    },
    deleteCollectionPoints(row) {
      this.$confirm('此操作将永久删除该采集点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delCollectPoint(row).then(res => {
          if (res.code == 20000) {
            this.$message.success('删除成功')
            this.getList()
          }
        }).catch(() => {

        })
      })
    },
    handleInvChange(invCode){
      this.invQuery.code = invCode
      getUsers( this.invQuery).then(res => {
        if (res.code == 20000){
          this.users = res.data || []
        }else {
          this.$message.error("错误")
        }
      })
    },
    append(data, formName) {//新增 编辑
      this.formName = formName;
      if (formName === "edit") {
        this.subData = JSON.parse(JSON.stringify(data));
        this.subData.name = JSON.parse(JSON.stringify(data.label));
      } else if (formName === "add") {
        this.subData = {
          parentCode: JSON.parse(JSON.stringify(data)).code
        };
        let parentData = {
          parentCode: JSON.parse(JSON.stringify(data)).code,
          parentName: JSON.parse(JSON.stringify(data.label))
        }
        this.fromDeptOptions.push(parentData)
      }
      this.subFormVisible = true;
    },
    forInvSubmit(){
      addTree(this.subData).then(res => {
        if (res.code == 20000){
          this.subFormVisible = false
          this.getTree()
          this.$message.success("成功")
        }else {
          this.$message.error(res.message)
        }
      })
    },
    delTree(row){
      deleteTree(row).then(res => {
        if (res.code == 20000){
          this.getTree()
          this.$message.success("删除成功")
        }else {
          this.$message.error("删除失败")
        }
      })
    },
    handCurrentChange(row){
      this.currentRow.name = row.name
      this.currentRow.code = row.code
    },
    addUser(){
      if (this.currentRow.code == null){
        return this.$message.error("请选择采集点!")
      }
      getUsers(this.currentRow).then(res => {
        if (res.code == 20000){
          this.users = res.data || []
        }else {
          this.$message.error("错误")
        }
      })
      this.adduserDialogVisible = true
    },
    getTree(){
      getTree(this.query)
        .then((response) => {
          var invlist = response.data || [];
          this.treeList = this.handleTree(invlist, "code", "parentCode");
        })
        .catch(() => {
        });
    }
  },
  created() {
    this.getList()
    this.getBusType()
    this.getInvList()
    this.getTree()
  }

}
</script>

<style scoped>
.dialog-footer {
  display: flex; /* 使用Flexbox布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.iconButton {
  margin-left: 0px;
  height: 30px;
}
</style>
