<template>
  <div class="app-container">
    <!-- 首页搜索 -->
    <el-form :model="formData" ref="formData" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="formData.keyWord"
          placeholder="请输入关键字"
          clearable
          maxlength="50"
          @keyup.enter.native="handleQuery"
        />
      </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">新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 列表 -->
    <el-table :data="houseList" :border="true">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="typeName" label="机具名称" min-width="280" align="center" />
      <el-table-column prop="typeModelName" label="规格型号" min-width="280" align="center" />
      <el-table-column prop="totalNum" label="套装所需配件数量" width="200" align="center" />
      <el-table-column label="操作" align="center" width="210" fixed="right">
        <template v-slot="{ row }">
          <el-button size="mini" type="primary" icon="el-icon-search" @click="handleDetail(row)">查看明细</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(row)">删除</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="70%" :close-on-click-modal="false">
      <!-- 新增 -->
      <el-form :model="dialogForm" ref="dialogForm" label-width="100px" :inline="true" size="small">
        <el-form-item
          label="物品类型"
          prop="parentId"
          :rules="[{ required: true, message: '请选择物品类型', trigger: 'change' }]"
          v-if="!isDetail"
        >
          <el-cascader
            v-model="dialogForm.parentId"
            placeholder="请选择物品类型"
            :options="typeOptions"
            filterable
            clearable
            @change="handleTypeOptions"
            style="width: 300px"
            v-if="!isDetail"
          />
        </el-form-item>

        <el-form-item
          ref="typeTree"
          label="选择配件"
          prop="mountingsValue"
          :rules="[{ required: true, message: '请选择配件', trigger: 'change' }]"
          v-if="!isDetail"
        >
          <el-cascader
            ref="mountingsTree"
            v-model="dialogForm.mountingsValue"
            placeholder="请选择配件"
            :options="mountingsOptions"
            :props="{ multiple: true }"
            filterable
            clearable
            @change="handleMountingsOptions"
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item label=" " label-width="50px" v-if="!isDetail">
          <el-button type="primary" size="mini" @click="addDialogList" icon="el-icon-plus">添加</el-button>
        </el-form-item>

        <!-- 详情 -->
        <el-form-item label="关键字" prop="keyWord" v-if="isDetail">
          <el-input
            v-model="dialogForm.keyWord"
            placeholder="请输入关键字"
            clearable
            maxlength="50"
            @keyup.enter.native=""
          />
        </el-form-item>
        <el-form-item v-if="isDetail">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="dialogList" border stripe>
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="typeName" label="类型名称" align="center" />
        <el-table-column prop="typeModelName" label="规格型号" align="center" />
        <el-table-column prop="totalNum" label="每付所需数量" align="center">
          <template v-slot="{ row }">
            <el-input-number v-model="row.totalNum" size="mini" :min="1" v-if="!isDetail" />
            <span v-else>{{ row.totalNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" v-if="!isDetail">
          <template v-slot="{ row }">
            <el-popconfirm
              title="确认删除该数据?"
              placement="top"
              icon="el-icon-info"
              @confirm="handleDeleteDialog(row)"
            >
              <el-button size="mini" type="danger" icon="el-icon-delete" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="open = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="dialogSubmit" :loading="isLoading" v-if="!isDetail">
          保 存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMaType, addMaWhole, searchSelectList, searchSelectListById, deleteById } from '@/api/store/poleConfig'
export default {
  name: 'poleConfig',
  data() {
    return {
      isLoading: false,
      showSearch: true,
      formData: {
        keyWord: '',
      },
      houseList: [],
      title: '新增',
      open: false,
      dialogForm: {
        parentId: '',
        mountingsValue: [],
        keyWord: '',
      },
      typeOptions: [],
      mountingsOptions: [],
      dialogList: [],
      selectList: [],
      isDetail: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '',
      },
      rowId: '',
    }
  },
  created() {
    this.getList()
    getMaType({ parentId: 1 }).then(res => {
      // 处理为typeOptions需要的数据格式
      const data = res.data
      this.typeOptions = this.getTree(data)
    })
    getMaType({ parentId: 2 }).then(res => {
      // 处理为mountingsOptions需要的数据格式
      const data = res.data
      this.mountingsOptions = this.getTree(data)
    })
  },
  methods: {
    // 获取列表
    async getList(data = {}) {
      this.queryParams.pageNum = data.page || 1
      this.queryParams.pageSize = data.limit || 10
      this.queryParams.keyWord = this.formData.keyWord || ''
      const res = await searchSelectList({ ...this.queryParams })
      console.log('🚀 ~ getList ~ res:', res);
      this.houseList = res.data.result
      this.total = res.data.totalCount || 0
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      const keyWord = this.formData.keyWord?.trim()
      this.getList({ keyWord })
    },
    handleSearch() {
      const keyWord = this.dialogForm.keyWord?.trim() || ''
      this.getDetail({ id: this.rowId, keyWord })
    },
    // 重置
    resetQuery() {
      this.formData.keyWord = ''
      this.getList()
    },
    resetSearch() {
      this.dialogForm.keyWord = ''
      this.getDetail({ id: this.rowId })
    },
    // 新增
    handleAdd() {
      // 打开新增弹窗
      this.open = true
      this.isDetail = false
      this.dialogList = []
      this.$nextTick(() => {
        this.$refs.dialogForm.resetFields()
      })
    },
    // 详情弹框
    handleDetail(row) {
      this.rowId = row.id
      this.open = true
      this.isDetail = true
      this.title = '抱杆配套明细'
      this.getDetail({ id: row.id })
    },
    // 获取详情
    async getDetail({ id, keyWord = '' }) {
      const res = await searchSelectListById({ id, keyWord })
      this.dialogList = res.rows
    },
    // 删除
    handleDelete(row) {
      // 提示
      this.$confirm('是否确认删除该数据?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 删除
          deleteById({ id: row.id }).then(() => {
            this.getList()
          })
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.info('取消删除')
        })
    },
    // 选择物品类型
    handleTypeOptions(val) {
      this.dialogForm.parentId = val[val.length - 1]
    },
    // 选择配件
    handleMountingsOptions(val) {
      this.dialogList = []
      this.dialogForm.mountingsValue = val
      const selected = this.$refs.mountingsTree.getCheckedNodes()
      // 过滤出 level = 2 的数据
      const filterSel = selected.filter(item => item.level === 2)
      this.selectList = filterSel.map(item => {
        return {
          typeId: item.value,
          typeName: item.pathLabels[0],
          typeModelName: item.label,
          totalNum: 1,
        }
      })
    },
    // 添加
    addDialogList() {
      // 表单校验
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          this.dialogList = this.selectList
        } else {
          // 提示
          this.$message.warning('请填写完整信息') // w
          return false
        }
      })
    },
    // 删除
    handleDeleteDialog(row) {
      console.log('🚀 ~ handleDeleteDialog ~ row:', row);
      // 根据row.parentId删除
      this.dialogList = this.dialogList.filter(item => item.typeId !== row.typeId)
    },
    getTree(data) {
      return data.map(item => {
        if (item.children && item.children.length) {
          return {
            value: item.id,
            label: item.label,
            children: this.getTree(item.children),
          }
        } else {
          return {
            value: item.id,
            label: item.label,
          }
        }
      })
    },
    // 保存
    async dialogSubmit() {
      // 表单校验
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          this.isLoading = true
          const MaWholeSetDto = {
            parentId: this.dialogForm.parentId,
            wholeList: this.dialogList,
          }
          addMaWhole(MaWholeSetDto)
            .then(() => {
              this.isLoading = false
              this.open = false
              this.$message.success('保存成功')
              this.getList()
            })
            .catch(() => {
              this.isLoading = false
            })
        } else {
          this.isLoading = false
          this.$message.warning('请填写完整信息')
          return false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
