<template>
  <Page>
    <ElForm v-show="showSearchForm" inline @submit.prevent="paging">
      <ElFormItem label="订单编号">
        <ElInput v-model="searchForm.sn" placeholder="订单编号" />
      </ElFormItem>
      <ElFormItem label="项目 Id">
        <ElInput v-model="searchForm.projectId" placeholder="项目 Id" />
      </ElFormItem>
      <ElFormItem label="下单人">
        <ElInput v-model="searchForm.userId" placeholder="下单人" />
      </ElFormItem>
      <ElFormItem label="下单人客户">
        <ElInput v-model="searchForm.customerId" placeholder="下单人客户" />
      </ElFormItem>
      <ElFormItem label="下单人姓名">
        <ElInput v-model="searchForm.contacts" placeholder="下单人姓名" />
      </ElFormItem>
      <ElFormItem label="下单人联系方式">
        <ElInput v-model="searchForm.phone" placeholder="下单人联系方式" />
      </ElFormItem>
      <ElFormItem label="下单时间">
        <ElInput v-model="searchForm.orderTime" placeholder="下单时间" />
      </ElFormItem>
      <ElFormItem label="订单类型">
        <ElInput v-model="searchForm.orderCategory" placeholder="订单类型" />
      </ElFormItem>
      <ElFormItem label="订单状态">
        <ElInput v-model="searchForm.orderStatus" placeholder="订单状态" />
      </ElFormItem>
      <ElFormItem label="完结时间">
        <ElInput v-model="searchForm.finishTime" placeholder="完结时间" />
      </ElFormItem>
      <ElFormItem label="运输企业">
        <ElInput v-model="searchForm.transOrgId" placeholder="运输企业"/>
      </ElFormItem>
      <ElFormItem label="指派清运公司时间">
        <ElInput v-model="searchForm.assignmentTransTime" placeholder="指派清运公司时间" />
      </ElFormItem>
      <ElFormItem label="站点">
        <ElInput v-model="searchForm.stationId" placeholder="站点" />
      </ElFormItem>
      <ElFormItem label="站点名称">
        <ElInput v-model="searchForm.stationName" placeholder="站点名称" />
      </ElFormItem>
      <ElFormItem label="预估量">
        <ElInput v-model="searchForm.estimatedQuantity" placeholder="预估量" />
      </ElFormItem>
      <ElFormItem label="预估车数">
        <ElInput v-model="searchForm.estimatedTrainNum" placeholder="预估车数" />
      </ElFormItem>
      <ElFormItem label="产品 Id">
        <ElInput v-model="searchForm.goodsId" placeholder="产品 Id" />
      </ElFormItem>
      <ElFormItem label="产品名称">
        <ElInput v-model="searchForm.goodsName" placeholder="产品名称" />
      </ElFormItem>
      <ElFormItem label="计量单位">
        <ElInput v-model="searchForm.unit" placeholder="计量单位" />
      </ElFormItem>
      <ElFormItem label="客户备注">
        <ElInput v-model="searchForm.customerMemo" placeholder="客户备注" />
      </ElFormItem>
      <ElFormItem label="创建人">
        <ElInput v-model="searchForm.creatorId" placeholder="创建人" />
      </ElFormItem>
      <ElFormItem label="修改人">
        <ElInput v-model="searchForm.modifierId" placeholder="修改人" />
      </ElFormItem>
      <ElFormItem label="创建时间">
        <ElInput v-model="searchForm.createTime" placeholder="创建时间" />
      </ElFormItem>
      <ElFormItem>
        <ElButton :icon="elIcons.Search" :loading="searching" native-type="submit" type="primary">搜索</ElButton>
        <ElButton :icon="elIcons.Refresh" :loading="searching" @click="reset">重置</ElButton>
      </ElFormItem>
    </ElForm>

    <div class="tool-bar">
      <!-- <ElButton :icon="elIcons.Plus" type="primary" @click="addHandler">新建</ElButton> -->
      <div></div>
      <ElButton :icon="elIcons.Filter" type="default" @click="showSearchForm = !showSearchForm" />
    </div>

    <ElTable v-loading="searching" @expand-change="treeLoad" :data="tableData" cell-class-name="table-cell" class="table-list" empty-text="暂无数据" header-row-class-name="table-header" row-key="id">
      <el-table-column type="expand">
        <template #default="props">
          <ElTable :data="props.row.children" header-row-class-name="table-header" :border="true" cell-class-name="table-cell" class="table-list">
            <ElTableColumn label="产品名称" prop="goodsName"/>
            <ElTableColumn label="清运状态" prop="transStatus" />
            <ElTableColumn label="订单状态" prop="orderStatus" />
            <ElTableColumn label="清运公司" prop="transOrgId" />
            <ElTableColumn label="操作" width="180" fixed="right">
              <template #default="scope">
                <div class="action-btn">
                  <ElButton text v-if="!scope.row.transOrgId" type="primary" @click="showAssignDialog(scope.row)">指派清运公司</ElButton>
                </div>
              </template>
            </ElTableColumn>
          </ElTable>
        </template>
      </el-table-column>
      <ElTableColumn label="订单编号" prop="sn" width="140" />
      <!-- <ElTableColumn label="项目 Id" prop="projectId" /> -->
      <ElTableColumn label="下单人" prop="contacts" />
      <ElTableColumn label="联系方式" prop="phone" width="120" />
      <ElTableColumn label="垃圾品类" prop="goodsName" />
      <ElTableColumn label="运输站点" prop="goodsName" />
      <!-- <ElTableColumn label="下单时间" prop="orderTime" />
      <ElTableColumn label="订单类型" prop="orderCategory"/>
        <ElTableColumn label="运输方客户 Id" prop="transCustomerId"/>-->
      <ElTableColumn label="运距（米）" prop="transDistance" width="120" />
      <ElTableColumn label="预估量" prop="estimatedQuantity" />
      <ElTableColumn label="预估车数" prop="estimatedTrainNum" />
      <!-- <ElTableColumn label="计量单位" prop="unit"/> -->
      <ElTableColumn label="客户备注" prop="customerMemo" />
      <ElTableColumn label="创建时间" prop="createTime" width="160" />
      <ElTableColumn label="修改时间" prop="modifyTime" width="160" />
      <ElTableColumn label="操作" width="180" fixed="right">
        <template #default="scope">
          <div class="action-btn">
            <ElPopconfirm confirm-button-text="是" cancel-button-text="否" confirm-button-type="danger" cancel-button-type="primary" placement="top" title="是否删除当前数据?" width="180" @confirm="delHandler(scope)">
              <template #reference>
                <ElButton text type="danger" :loading="deling">删除</ElButton>
              </template>
            </ElPopconfirm>
            <!-- <ElButton text type="primary" @click="modifyHandler(scope)">修改</ElButton> -->
          </div>
        </template>
      </ElTableColumn>
    </ElTable>
    <ElPagination layout="->, sizes, total, prev, pager, next" v-model:current-page="searchForm.current" v-model:page-size="searchForm.size" :total="totalCount" :page-sizes="[10, 20, 50, 100, 500]" :hide-on-single-page="false" :teleported="false" @change="paging" />
    <OrderForm ref="orderForm" @edit-succ="paging" />

    <ElDialog v-model="assignDialog" :destroy-on-close="true" title="指派清运公司" width="500">
      <div style="display: flex; align-items: center">
        <span style="margin-right: 10px">选择公司：</span>
        <ASelect labelKey="orgName" valueKey="id" :tableColumn="customerColumn" v-model="assignFrom.transOrgId" :api="OrgApi.paging" placeholder="请选择清运公司" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="assignDialog = false">关闭</ElButton>
          <ElButton type="primary" @click="confirmDialog"> 确认 </ElButton>
        </div>
      </template>
    </ElDialog>
  </Page>
</template>

<script lang="ts" setup>
import OrderApi from '@/pages/order/book-order/order-api.ts'
import OrderForm from '@/pages/order/book-order/OrderForm.vue'
import Page from '@/components/page/Page.vue'
import { elIcons } from '@/common/element/element.ts'
import Utils from '@/common/utils'
import OrgApi from '@/pages/cst/org/org-api.ts'
import ASelect from '@/components/a-select/ASelect.vue'

const totalCount = ref(0);
const tableData = Utils.resetAble(reactive<OrderTypes.SearchOrderResult[]>([]));
const searchForm = Utils.resetAble(
  reactive<OrderTypes.SearchOrderParam>({
    current: 1,
    size: 20,
  })
);
const searching = ref(false);
const deling = ref(false);
const showSearchForm = ref(true);
const assignDialog = ref(false);
// const orderFormIns = useTemplateRef<InstanceType<typeof OrderForm>>("orderForm");
const assignFrom = ref({
  transOrgId: "",
  orderTransId: "",
});

function treeLoad(row: any, expanded: any, resolve: (data: any[]) => void) {
  if (resolve == null && !expanded) return;
  searching.value = true;
  OrderApi.orderTrans({ sn: row.sn })
    .then((res) => {
      console.log(resolve, "res.data");
      row.children = res.data?.records;

      //  if (resolve!=null){
      //    resolve(res.data?.records.map((it:any) => {
      //      it.hasChildren = true
      //      return it
      //    }) ?? [])
      //    console.log(res.data?.records)
      //  } else {
      //    tableData.updateKeyChildren(row.id, res.data?.records.map(it => {
      //      it.hasChildren = true
      //      it.children = []
      //      return it
      //    }) ?? [])
      //  }
    })
    .finally(() => {
      searching.value = false;
    });
}

const customerColumn = [
  {
    label: "公司",
    prop: "orgName",
  },
  {
    label: "公司类型",
    prop: "customerList[0].identityCategoryTxt",
  },
  {
    label: "地区",
    prop: "areaName",
  },
  {
    label: "统一社会编码",
    prop: "uscc",
  },
];

function showAssignDialog(data: any) {
  assignFrom.value.transOrgId = data.transOrgId;
  assignFrom.value.orderTransId = data.id;
  assignDialog.value = true;
}

function confirmDialog() {
  console.log(assignFrom.value, "assignFrom");
  if (!assignFrom.value.transOrgId) {
    ElMessage.error("请选择清运公司");
    return;
  }
  OrderApi.assignmentOrg(assignFrom.value).then(() => {
    assignDialog.value = false;
    ElMessage.success("派车成功");
  });
}


function delHandler({ row }: { row: OrderTypes.SearchOrderResult }) {
  deling.value = true;
  OrderApi.del([row.id!])
    .then(() => {
      ElMessage.success("删除成功");
      paging();
    })
    .finally(() => {
      deling.value = false;
    });
}

// function modifyHandler({ row }: { row: OrderTypes.SearchOrderResult }) {
//   showDialog(row);
// }

function reset() {
  searchForm.$reset();
  paging();
}

function paging() {
  searching.value = true;
  OrderApi.paging(searchForm)
    .then((res) => {
      totalCount.value = res.data?.total ?? 0;
      tableData.$reset(res.data?.records ?? []);
    })
    .finally(() => {
      searching.value = false;
    });
}
onMounted(() => {
  paging();
});
</script>

<style lang="stylus" scoped>
.table-list {
  flex 1;
  margin 0 0 20px 0
  width 100%

  :deep(.table-header) {
    color #454C59

    th {
      background-color #EDF1F7
      font-weight 500
      position relative

      & > div {
        display flex
        gap 5px
        align-items center
      }

      &:not(:first-child) > div::before {
        position: absolute;
        top: 50%;
        left: 1px;
        width: 1px;
        background-color: #D3D7DE;
        transform: translateY(-50%);
        content: "";
        height 50%
      }
    }
  }

  :deep(.table-cell) {
    color #2F3540
  }
  .action-btn {
    width 100%
    display flex
    flex-wrap wrap

    & > button {
      margin 0
    }
  }
}

.tool-bar {
  display flex
  justify-content space-between
  margin 0 0 20px 0
}
</style>
