<script setup lang="ts">
import { ref, shallowRef,  watch } from "vue";
import { useAsync, useResponseHandle } from "/@/hooks/core/useAsync";
import { httpList, httpStatus } from "/@/api/serviceParam/grossProfit";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { statusOptions, khOptions } from "../_options";
import { ElMessageBox, ElMessage } from "element-plus"
import Modal from "./modal.vue"
import { useCompany } from "/@/hooks/core/useCompany";
const { currentCompany } = useCompany()


const emit = defineEmits(["breadcrumbChange"]);
const props = defineProps<{ otherParms: Record<string, string>; breadcrumb: any[] }>();



const pid = ref("")
const dataSource = ref<any>({})
const visible = shallowRef(false)
const responseHandle = useResponseHandle()

const { data, loading, run } = useAsync<any>({ isList: true });
function toNextNode(depart: any) {
  pid.value = depart.cat_id;
  requestCategorylist();
  emit("breadcrumbChange", depart);
}

function requestCategorylist() {
  if(!currentCompany.value.companyNo){
    ElMessage.warning('请在右上角选择一家业务公司!')
    loading.value = false
    data.value = []
    return
  }

  const params = { 
    ...props.otherParms, 
    ...(pid.value ? { pid: pid.value } : { pid : 0 }), 
    size: 1000,
    companyNo: currentCompany.value.companyNo 
  }


  run(httpList(params));
}

const initialData = () => requestCategorylist()
function onDelete(id: string) {
  ElMessageBox.confirm('确认要删除?', { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }).then(async () => {
    const model = { id }
    const res = await httpDelete(model)
    if (res.code === 0) {
      ElMessage.success('删除成功')
      requestCategorylist()
    } else {
      ElMessage.warning('删除失败')
    }
  })
}


function onEdit(row: any = {}) {
  console.log(row)

  const { cat_id, cat_name, order_rate , sale_rate , rate , low_rate } = row;
  dataSource.value = { id: cat_id, cat_name , order_rate : order_rate || 0, sale_rate : sale_rate || 0, rate : rate || 0, low_rate: low_rate || 0 }
  visible.value = true
}


const handleStatus = async row => {
  const { cat_id, status, companyNo } = row;
  const { code, message } = await httpStatus({ companyNo: currentCompany.value.companyNo, status: status + "" === "1" ? "0" : "1", cat_id })

  responseHandle({
    code,
    message,
    handler: () => requestCategorylist()
  });
};


initialData();
watch(() => currentCompany.value, requestCategorylist)
defineExpose({ changePid: (id: string) => (pid.value = id), onSearch: () => requestCategorylist() });
</script>

<template>
  <ul class="mt-[10px]" v-loading="loading">
    <ElTable :data="data" border size="small" max-height="calc(100vh - 160px)">
      <ElTableColumn label="分类名称" prop="cat_name" min-width="160px" show-overflow-tooltip />
      <ElTableColumn label="状态" prop="status" min-width="70px">
        <template #="{ row }">
          <ElTag :type="String(row.status) === '0' ? 'warning' : ''">{{ statusOptions.find(({ value }) => value === String(row.status))?.label || '--' }}</ElTag>
        </template>
      </ElTableColumn>

      <ElTableColumn label="分类等级" prop="level" min-width="80px" />

      <ElTableColumn label="操作" width="140px">
        <template #="{ row }">
          <el-tooltip effect="dark" content="编辑专属分类" placement="top">
            <ElButton link class="reset-margin" type="primary" :icon="useRenderIcon('edits')" @click="onEdit(row)" />
          </el-tooltip>

          <el-popconfirm :title=" String(row.status) === '1' ? '改为禁用？' : '改为启用？'" @confirm="handleStatus(row)"  >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  size="small"
                  :icon=" useRenderIcon(String(row.status) === '1' ? 'close-circle-line' : 'checkbox-circle-line')" />
                </template>
              </el-popconfirm>
              <el-tooltip effect="dark" content="下一级" placement="top">
            <ElButton link class="reset-margin" type="primary" :icon="useRenderIcon('arrow-right-s-line')"  @click="toNextNode(row)" />
          </el-tooltip>
        </template>
      </ElTableColumn>
    </ElTable>

    <Modal 
      :pid="pid" 
      v-model:data="dataSource" 
      v-model:visible="visible" 
      :breadcrumb="breadcrumb"  
      @refresh="requestCategorylist" 
    />
  </ul>
</template>
