<template>
  <div>
    <crud-template ref="crudRef" class="as-weight" :submit-state="false" :home-data="field" :tableData="tableData"
      @btnSearch="btnSearch" @CurrentChange="handleCurrentChange" @importData="importData" @download="downloadHandle"
      @refreshLeft="refreshLeft" @add="Adds" @cancel="cancel" @submit="submitAdd"
      @customSelectorSelection="customSelectorSelection" @handleEdit="handleEdit" @handleDelete="deleteHandle">
      <template #search>
        <el-input maxlength="60" v-trim clearable v-model="searchForm.agencyId" style="width: 200px"
          placeholder="请输入渠道编号" />
        <el-input maxlength="60" v-trim clearable v-model="searchForm.code" style="width: 200px"
          placeholder="请输入仓库编号" />
        <el-input maxlength="60" v-trim clearable v-model="searchForm.name" style="width: 200px"
          placeholder="请输入仓库名称" />
        <el-date-picker unlink-panels v-model="value1" type="daterange" range-separator="到" start-placeholder="开始日期"
          end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="dateChangeHandle" style="width: 250px"/>
      </template>
      <template #operation="{scope}">
        <el-button v-if="scope.row.code!=='5201010304001900000'" type="success" size="small" @click="toEdit(scope.row)">修改</el-button>
        <el-button type="primary" size="small" @click="showInfo(scope.$index, scope.row)">详情</el-button>
      </template>
      <template #isCheck="item">
        <!-- @vue-ignore -->
        <el-switch v-model="item.scope.row.isCheck" :active-value="1" :inactive-value="0" active-color="#13ce66"
          inactive-color="#ff4949" @click="handleBeforeChange1(item.scope.row.isCheck, item.scope.row)"></el-switch>
      </template>
    </crud-template>
    <el-dialog title="详情" v-model="dialogVisible">
      <el-descriptions direction="vertical" :column="3" border>
        <el-descriptions-item class-name="my-content" v-for="item in info" :label="item.label" width="33.3%">
          {{ item.value }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, nextTick, toRaw } from 'vue'
// @ts-ignore crudFrom模板
import CrudTemplate from '@/crud/index.vue'
import BaseService from '@/utils/baseService' //引入接口请求
import {
  ElMessage,
} from 'element-plus' //提示
import { getZxqdFindConfig } from "./data.js";
import { useRoute } from 'vue-router'
import { exportFn } from '@/views/settlement/exportFn'
//或取路由传入过来的对象数据
const route = useRoute()
const widthBase = '120px';
const crudRef = ref()
const value1 = ref()
let tableData: any = ref([])
const itemStartValue = ref(1)
//查询参数
const searchForm = ref({ agencyId: '' })
const agencyIdList = ref([])
const branchIdList = ref([])
const hallList = ref([])
const upperWarehouseIdList = ref([])
const info = ref({})
const dialogVisible = ref(false)
const field = ref(getZxqdFindConfig(route, agencyIdList, branchIdList, upperWarehouseIdList,hallList));
onMounted(() => {
  getList()
  getAgenCy()
  getUpperWarehouseIdList()
})
function getAgenCy() {
  BaseService.post('/userw/agency/agencyqueryall', {}).then((res: any) => {
    if (res && res.statusCode === 0) {
      //数据转换 .agencyQueryAllModels
      let bizContent = res.data
      agencyIdList.value = bizContent.map((item) => {
        return { label: item.name, value: item.agencyId }
      })
      // console.log(agencyIdList.value, 'agencyIdList.value')
    } else {
      ElMessage.error(res.message)
    }
  })
}
function dateChangeHandle(val: any) {
  if (val) {
    searchForm.value.insertTimeStart = val[0];
    searchForm.value.insertTimeEnd = val[1];
  } else {
    searchForm.value.insertTimeStart = "";
    searchForm.value.insertTimeEnd = "";
  }
}
function handleBeforeChange1(value, arg1) {
  // console.log(value, arg1);
  BaseService.post('/invw/api/warehouse/check', { id: arg1.id, isCheck: value }).then((res: any) => {
    if (res && res.statusCode === 0) {
      if (value == '1') {
        ElMessage.success('库存校验开启')
      } else {
        ElMessage.error('库存校验关闭')
      }
      getList()
    } else {
      ElMessage.error(res.message)
    }
  })
}
function getUpperWarehouseIdList() {
  BaseService.post('/invw/api/warehouse/getWarehouseIdNames', {
    "id": "999",
    "type": "8"
  }).then((res: any) => {
    if (res && res.statusCode === 0) {
      //数据转换 .agencyQueryAllModels
      let bizContent = res.data.idNames
      upperWarehouseIdList.value = bizContent.map((item) => {
        return { label: item.name, value: item.id }
      })
    } else {
      ElMessage.error(res.message)
    }
  })
}
//选择变化监听
function customSelectorSelection(value, title, form, item, dialogArray) {
  // console.log('value',value, title, form, item, dialogArray);
  if (title == 'agencyId') {
    if(value !==null && value !== undefined && value!=="") {
      BaseService.postN('/userw/serviceHall/serviceHallGetByAgencyId', {agencyId: value}).then((res: any) => {
        if (res && res.code === 0) {
          let data = res.data || {}
          hallList.value = data.map((item) => {
            return { label: item.servicehallName, value: item.servicehallId }
          })
        }
      })
    }
  }
}
// 修改
function toEdit(row) {
    const data: any = toRaw(row)
    crudRef.value.dialogFormVisible = true
    crudRef.value.title = '编辑'
    itemStartValue.value = 2
    nextTick(() => {
      crudRef.value.form={
        ...data
      }
      customSelectorSelection(row.agencyId, 'agencyId',null, null, null)
    })
  }

//详情
function showInfo(idx: any, row: any) {
  let labels = field.value.field

  const result: Record<string, any> = {}; // 临时存储结果

  // 遍历 labels，提取 label 和对应的 value 剔除labels的isCheck
  labels = labels.filter(item => item.prop !== 'isCheck');
  labels.forEach((fieldConfig) => {
    const { prop, label } = fieldConfig;
      result[prop] = {
        label: label, // 显示名称
        value: row[prop] ?? '--', // 对应 row 的值
      };
  });

  info.value = result; // 更新响应式数据

  // console.log('info.value', info.value)

  dialogVisible.value = true
}
// 导出
function downloadHandle() {
  exportFn('/invw/api/qrySmObuBatch/export', searchForm.value, 'OBU发行批次')
}
//获取列表
function getList() {
  crudRef.value.tableLoding = true
  let params: any = {
    pageNo: field.value.paging.currentPage,
    pageSize: field.value.paging.pageSize,
  }
  //赋值查询参数
  let searchFormList = { ...searchForm.value }
  for (let key in searchFormList) {
    if (searchFormList[key]) {
      params[key] = searchFormList[key]
    }
  }
  BaseService.postN('/invw/api/warehouse/page', params).then((res: any) => {
    if (res && res.code === 0) {
      //数据转换
      let bizContent = res.data
      let data = bizContent.result || []
      //数据渲染
      tableData.value = data
      crudRef.value.tableLoding = false
      //分页总数
      field.value.paging.total = bizContent.totalCount
    } else {
      crudRef.value.tableLoding = false
      ElMessage.error(res.message)
    }
  })
}

const Adds = () => {
  itemStartValue.value = 1
}
//表单编辑按钮
function handleEdit(idx: any, row: any) {
  itemStartValue.value = 2
}

// 添加
const submitAdd = (data: any) => {
  request(data, itemStartValue.value)
}

const request = (data: any, type: any) => {
  //操作类型 1新增 2修改
  BaseService.postN(type == 1 ? '/invw/api/warehouse/add' : '/invw/api/warehouse/edit', data).then((res: any) => {
    if (res && res.code === 0) {
      getList()
      getAgenCy()
      getUpperWarehouseIdList()
      crudRef.value.reset();
      crudRef.value.dialogFormVisible = false;
    }
  })
}
// 删除
const deleteHandle = (idx: any, row: any) => {
  BaseService.postN('/userw/centerServiceHall/delete', row).then((res: any) => {
    if (res && res.code === 0) {
      getList()
      crudRef.value.reset();
      crudRef.value.dialogFormVisible = false;
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 搜索按钮
function btnSearch() {
  field.value.paging.currentPage = 1
  getList()
}

//标签分页
function handleClick(tab, event) {
  orderStep.value = tab.props.name
  getList()
}

//分页
function handleCurrentChange(val: number) {
  field.value.paging.currentPage = val
  getList()
}
function handleAvatarSuccess(response: any, row) {

}
// 搜索重置
function refreshLeft() {
  searchForm.value = {}
  getList()
}

// 获取所有渠道
function getAgencyList() {

}

// 删除
function handleDetele() {

}

// 取消
function cancel() {

}
</script>
<style scoped>
:deep(.my-content){
  word-break: break-all;
}
</style>
