<template>
  <div>
    <SearchBox ref="SearchBoxRef" formName="selectTop" :formData="query" @showPop="showPop" @reset="reset"></SearchBox>
    <ButtonBox @search="handleSearch" @add="insertDialog" @start="start('0')" @remove="shutdwon('1')"></ButtonBox>

<!--    <TableBox ref="TableBoxRef" :tableData="tableData" @edit="handleEdit" @remove="handleRemove" :page="pageType"-->
<!--              :url="url" :param="query" @handleSelectionChange="handleSelectionChange"></TableBox>-->
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row   @selection-change="handleSelectionChange" :height="height"  >
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="storeCd" label="库房编码" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="storeNm" label="库房名称" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
<!--          <template #default="scope">-->
<!--            <el-button @click="handleInfo(scope.row)" type="primary" link>{{ scope.row.itemNm }}</el-button>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column v-if="true" prop="areaCd" label="区号" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="stackCd" label="垛位号" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="storeType" label="库房类型" width="150" header-align="center" :formatter="formatter"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="activeStatus" label="生效状态" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.activeStatus == 0">{{ formatterStr( "status",scope.row.activeStatus) }}</el-tag>
            <el-tag type="info" v-else-if="scope.row.activeStatus == 1">{{ formatterStr( "status",scope.row.activeStatus) }}</el-tag>
            <el-tag  v-else>{{ formatterStr( "status",scope.row.activeStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="addName" label="添加人" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="addTime" label="添加时间" width="200" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="remarks" label="备注"  header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="200px" fixed="right">
          <template #default="scope">
            <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button plain type="danger" @click="handleRemove(scope.row )">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                     background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <el-dialog class="diaClass"  :close-on-click-modal="false" draggable title="新增" v-model="dialogVisible" width="40%" top="5vh"
               @open="openDialog">
      <el-card  >
      <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="库房类型" prop="storeType">
              <SelectorComponent  :optionList="dictList.STORE_TYPE" :value="form.storeType"
                                 @change="storeTypeDict"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库房名称" prop="storeNm">
              <el-autocomplete
                  v-model="form.storeNm"
                  :fetch-suggestions="querySearchSignReqNm"
                  placeholder="请输入库房名称"
                  @change="querySearchSignReqNmChange"
                  clearable

                  @select="handleBlur"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区号" prop="areaCd">
              <el-autocomplete
                  v-model="form.areaCd"
                  :fetch-suggestions="querySearChareaCd"
                  placeholder="请输入区号"
                  @change="querySearChareaCdChange"
                  clearable

                  @select="handleBlurQh"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="垛位号" prop="stackCd">
<!--              <el-autocomplete-->
<!--                  v-model="form.stackCd"-->
<!--                  :fetch-suggestions="querySearChareaCd"-->
<!--                  placeholder="请输入垛位号"-->
<!--                  clearable-->
<!--              ></el-autocomplete>-->
              <el-input v-model="form.stackCd"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                  v-model="form.remarks"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  placeholder=""
              />
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>

      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" plain @click="handleInsert(ruleFormRef)">保存</el-button>
          <el-button type="danger" plain @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog class="diaClass"  :close-on-click-modal="false" draggable title="编辑" v-model="dialogVisibleEdit" width="40%" top="5vh"
               @open="openDialog">
      <el-card :body-style="cardBodyStyle">
      <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="库房类型" prop="storeType">
              <SelectorComponent  :optionList="dictList.STORE_TYPE" :value="form.storeType"
                                 @change="storeTypeDict"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库房名称" prop="storeNm">
              <el-autocomplete
                  v-model="form.storeNm"
                  :fetch-suggestions="querySearchSignReqNm"
                  placeholder="请输入库房名称"
                  @change="querySearchSignReqNmChange"
                  clearable

                  @select="handleBlur"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区号" prop="areaCd">
              <el-autocomplete
                  v-model="form.areaCd"
                  :fetch-suggestions="querySearChareaCd"
                  placeholder="请输入区号"
                  @change="querySearChareaCdChange"
                  clearable

                  @select="handleBlurQh"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="垛位号" prop="stackCd">
<!--              <el-autocomplete-->
<!--                  v-model="form.stackCd"-->
<!--                  :fetch-suggestions="querySearChareaCd"-->
<!--                  placeholder="请输入垛位号"-->
<!--                  clearable-->
<!--              ></el-autocomplete>-->
              <el-input v-model="form.stackCd"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                  v-model="form.remarks"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  placeholder=""
              />
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>

      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" plain @click="handleSave(ruleFormRef)">保存</el-button>
          <el-button type="danger" plain @click="handleCancelSave2">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'

import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import tools from '@/tools'
import Attachment from '@/components/Attachment.vue'
import ButtonBox from "@/components/ButtonBox.vue";
import SearchBox from "@/components/SearchBox.vue";
import SelectorComponent from "@/views/sal/components/Selector_component.vue";

const {
  proxy
} = getCurrentInstance()

const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)



const PopupMenuTreeRef = ref(null)
const showPop = () => {
  console.log('showPop')
  PopupMenuTreeRef.value.show()
}
const url = ref('sto/Config/query')
const pageType = ref(true)

/**
 *   查询
 */
const form = ref({
  storeNm: '',
  areaCd: '',
  stackCd: '',
  storeType: '',
  id1: '',
  id2: '',
  id3: '',
});
/*method方法调用后端接口查询子类的值*/


const query = ref({
  storeNm: '',
  areaCd: '',
  stackCd: '',
  storeType: ''
})
const tableData = ref([])
const TableBoxRef = ref(null)
const handleSearch = () => {
  // TableBoxRef.value.search()
  getTableData()
}



/*绑定监听*/

// 定义一个方法
const handleBlur = (item) => {

  console.log(item)
  form.value.id1 = item.id
};
const querySearChareaCdChange = (item) => {

  console.log('通过input，将id2，清除·····')
  // form.value.id2 = ''
};
const querySearchSignReqNmChange = (item) => {

  console.log('通过input，将id1，清除·····')
  // form.value.id1 = ''
};
const handleBlurQh = (item) => {

  console.log("区号选择···",item)
  form.value.id2 = item.id
};

// 定义一个方法来获取建议
const querySearchSignReqNm = (queryString, cb) => {
  var ss = []
  if (form.value.storeType == '' || form.value.storeType == null){
    return cb(ss);
  }
  var url = 'sto/Config/queryAllKF'
  var obj = {
    storeType: form.value.storeType,
    activeStatus: '0',
    storeNm: form.value.storeNm
  }
  var param = {
    params: JSON.stringify(obj),
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(  response.data.data.records)
      response.data.data.records.forEach((item) => {
        ss.push({value :item.storeNm , id: item.id})
      })
      cb(ss);
      console.log('ss' , ss)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
      cb(ss);
    }
  })
};

const querySearChareaCd = (queryString, cb) => {
  var ss = []
  if (form.value.id1 == '' || form.value.id1 == null){
    return cb(ss);
  }

  var url = 'sto/Config/queryAllQH'
  var obj = {
    fId: form.value.id1,
  }
  var param = {
    params: JSON.stringify(obj),
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(  response.data.data.records)
      response.data.data.records.forEach((item) => {
        ss.push({value :item.areaCd , id: item.id})
      })
      cb(ss);
      console.log('ss' , ss)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
      cb(ss);
    }
  })
};

const querySearchStackCd = (queryString, cb) => {
  var ss = []
  var url = 'sto/Config/queryAll'
  var obj = {
    fId: form.value.id_2,
  }
  var param = {
    params: JSON.stringify(obj),
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(  response.data.data.records)
      response.data.data.records.forEach((item) => {
        ss.push({value :item.storeNm})
      })
      cb(ss);
      console.log('ss' , ss)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
      cb(ss);
    }
  })
};

/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([ 10, 20, 30, 40])
const pageSize = ref(10)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const dialogVisible = ref(false)
const dialogVisibleEdit = ref(false)

const ruleFormRef = ref()

const rules = reactive({
  storeType: [
    {required: true, message: '不允许为空', trigger: 'change'},
  ],
  storeNm: [
    {required: true, message: '不允许为空', trigger: 'change'},
  ],
  areaCd: [
    {required: true, message: '不允许为空', trigger: 'change'},
  ],
  stackCd: [
    {required: true, message: '不允许为空', trigger: 'change'},
  ],

})

const insertDialog = () => {
  form.value = {
    storeNm: '',
    areaCd: '',
    stackCd: '',
    storeType: '',
    activeStatue: '',
    remarks: ''
  }
  dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */
const refUpload = ref()

const openDialog = () => {

}


const handleSave = (ruleFormRef) => {
  if (!ruleFormRef) return
  ruleFormRef.validate((valid) => {
    if (valid) {
      console.log('submit!')
      var url = 'sto/Config/save'
      var param = {
        json: JSON.stringify(form.value),

      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          dialogVisibleEdit.value = false
          handleSearch()
        } else {
          ElMessage({
            type: 'error',
            message: '操作失败' + response.data.msg
          })
        }
      });
    } else {
      console.log('error submit!')
      return false
    }
  })
};
const handleInsert = (ruleFormRef) => {
  if (!ruleFormRef) return
  ruleFormRef.validate((valid) => {
    if (valid) {
      console.log('submit!')
      var url = 'sto/Config/insert'
      var param = {
        json: JSON.stringify(form.value),

      }
      console.log('form.value!' ,form.value)
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          dialogVisible.value = false
          handleSearch()
        } else {
          ElMessage({
            type: 'error',
            message: '操作失败' + response.data.msg
          })
        }
      });
    } else {
      console.log('error submit!')
      return false
    }
  })
};

const handleCancelSave = () => {
  dialogVisible.value = false
}
const handleCancelSave2 = () => {
  dialogVisibleEdit.value = false
}

const handleEdit = (row) => {
  if (row.activeStatus == '0') {
    ElMessage({
      type: 'warning',
      message: '数据生效中，不允许操作！'
    })
    return
  }

  var url = 'sto/Config/queryByPK'
  var param = {
    id: row.id
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      // Object.assign(insertForm, {
      //   ...response.data.data,
      // });

      form.value = response.data.data
      console.log(form.value)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
  dialogVisibleEdit.value = true
}

const handleRemove = (row) => {
  if (row.activeStatus == '0' || row.activeStatus == '1') {
    ElMessage({
      type: 'warning',
      message: '数据非新增状态，不允许操作！'
    })
    return
  }
  var url = 'sto/Config/remove'
  var param = {
    id: row.id
  }
  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        proxy.$axios.get(url, param).then(response => {
          if (response.data.code == '0') {
            console.log(response.data.data)
            ElMessage({
              type: 'success',
              message: '删除成功！',
            });
            getTableData()
            // TableBoxRef.value.search()
          } else {
            ElMessage.error('操作失败！' + response.data.msg)
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })


}

const start = (param) => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要生效的数据!'
    })
    return
  }
  edit('生效', param)

}

const shutdwon = (param) => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要失效的数据!'
    })
    return
  }
  edit('失效', param)

}

const edit = (title, val) => {
  var ids = []
  for (var i = 0; i < multipleSelection.value.length; i++) {
    ids.push(multipleSelection.value[i].id)
    ids.push(multipleSelection.value[i].id1)
    ids.push(multipleSelection.value[i].id2)
  }

  var param = {
    ids: JSON.stringify(ids),
    status: val
  }
  var url = 'sto/Config/startAndShutDown'
  ElMessageBox.confirm(
      '此操作将' + title + '该数据, 是否继续?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        proxy.$axios.post(url, param).then(response => {
          if (response.data.code == '0') {

            ElMessage({
              type: 'success',
              message: title + '成功！',
            });

            getTableData()
            // TableBoxRef.value.search()
          } else {
            ElMessage.error('操作失败！' + response.data.msg)
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })


}

/**
 * 保存、修改、删除
 */

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleRemoveBatch = () => {
  console.log('handleRemoveBatch')

  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据!'
    })
    return
  }

  ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var ids = []
    multipleSelection.value.forEach((item, index) => {
      ids.push(item.id)
    })
    /* var url = 'cot/SignRequest/removeBatch'*/
    var param = {
      ids: JSON.stringify(ids)
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        getTableData()
        dialogVisible.value = false
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const handleEditBatch = () => {
  console.log('handleEditBatch')
  if (multipleSelection.value.length != 1) {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据编辑!'
    })
    return
  }
  handleEdit(multipleSelection.value[0])
}

const handleUpload = () => {
  console.log('handleUpload')
}

const handleDownload = () => {
  console.log('handleDownload')
}

const handleImport = () => {
  console.log('handleImport')
}

const handleExport = () => {
  console.log('handleExport')
}
const dictList = ref({})

const dictData = () => {
  var url = 'framework/Common/querySelectorList'
  var param = {
    type: JSON.stringify(['STORE_TYPE' , 'START_STATUS'])
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      dictList.value = response.data.data
      console.log(response.data.data)

    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


const storeTypeDict = (val) => {
  form.value.storeType = val
}
const getTableData = () => {
  var url = 'sto/Config/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    storeNm: query.value.storeNm,
    areaCd: query.value.areaCd,
    stackCd: query.value.stackCd,
    storeType: query.value.storeType,
    json: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const formatterStr = (col,value) => {
  if (!value || value == null || value == '') {
    return value
  }

  switch (col) {
    case 'status':
      value = dictList.value && Array.isArray(dictList.value.START_STATUS)
          ? dictList.value.START_STATUS.find(item => item.dicCode == value)?.dicName
          : undefined
      break
  }
  return value

}
const height = ref(600)
const updateViewportHeight = () => {
  height.value = window.innerHeight * 0.65
  console.log( window.innerHeight);
};

const formatter = (row, column, cellValue, index) => {
  if (!cellValue || cellValue == null || cellValue == '') {
    return cellValue
  }
  switch (column.property) {
    case 'storeType':
      cellValue = dictList.value && Array.isArray(dictList.value.STORE_TYPE)
          ? dictList.value.STORE_TYPE.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break
  }
  return cellValue

}
onMounted(() => {
  dictData()
  getTableData()
  updateViewportHeight()



})
</script>

<style scoped>
::v-deep .diaClass .el-form-item {
  width: 100%
}
::v-deep .el-autocomplete{
  width: 100%;
}
::v-deep .el-dialog__body {
  background-color: #F2F6FC;
}
</style>
