<template>
  <div class="row" style="padding: 35px">
    <fln-table
      :config="state.tableConfig"
      :refreshCount="state.tableConfig.refreshCount"
      :refreshCountWithPagination="state.tableConfig.refreshCountWithPagination"
      @triggerRowActions="handleRowActions"
      @triggerTableBatchActions="handleBatchActions"
    >
      <template #search-header>
        <div
          class="col-12 row font-18"
          style="
            color: #764cf6;
            border-bottom: 1px solid #c1b2e5;
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div
            class="fl-py-sm font-bold theme-color"
            style="border-bottom: 4px solid"
          >
            退画管理
          </div>
        </div>
      </template>
      <template #table-header-box>
        <n-button
          type="primary"
          style="
            width: 161px;
            height: 34px;
           
            color: #fff;
            border-radius: 3px;
          "
          
          class="fl-mb-md"
          :loading="state.btnLoading"
          @click="handleInitiate"
        >
          发起
        </n-button>
      </template>
    </fln-table>

    <n-modal
      v-model:show="state.dialogAddOne"
      style="width: 600px"
      :mask-closable="false"
      preset="card"
    >
      <template #header>
        <div
          class="col-12 row justify-center relative theme-color" 
          style="border-bottom: 1px solid #dfd7f2"
        >
          <div style="font-size: 20px; font-weight: bold;">
            一键添加快递信息
          </div>
        </div>
      </template>

      <div class="row justify-center fl-pa-md">
        <div class="font-20 row items-center" style="margin: 115px 0">
          <div class="fl-mr-md">快递单号</div>
          <div>
            <n-input
              v-model:value="state.dialogAddOneData.trackingNo"
              placeholder="请输入快递单号"
            />
          </div>
        </div>
        <div class="col-12 row justify-center">
          <n-button
            tertiary
            class="fl-mr-md theme-color"
            style="width: 161px;"
            @click="state.dialogAddOne = false"
            >取消</n-button
          >
          <n-button
            type="primary"
            style="width: 161px; color: #fff"
            @click="handleDialogAddOneConfirm"
            :loading="state.btnLoading"
            >确认</n-button
          >
        </div>
      </div>
    </n-modal>

    <n-modal
      v-model:show="state.dialogInitiate"
      style="width: 1200px"
      :mask-closable="false"
      preset="card"
    >
      <template #header>
        <div
          class="col-12 row justify-center relative"
          style="border-bottom: 1px solid #dfd7f2"
        >
          <div style="font-size: 20px; font-weight: bold; color: #1f2225ff">
            发起退画
          </div>
        </div>
      </template>

      <div class="row justify-center fl-pa-md">
        <div class="col-12 fl-mb-md">
          <!-- tableType="one" -->

          <fln-table
            :config="state.initiateConfig"
            :refreshCount="state.initiateConfig.refreshCount"
            :pagination="{
              pageSize: 5,
              pageSizeOptions: [5, 10],
            }"
            :defaultSelectedRows="state.initiateConfig.defaultSelectedRows"
            @triggerSelectCheck="handleTableSelectCheck"
          >
            <template #table-header-box>
              <div class="col-12 row justify-between">
                <div>画作信息</div>
                <div v-if="state.selectedRows.length > 0">
                  您已勾选 {{ state.selectedRows.length }} 幅画作
                </div>
              </div>
            </template>
          </fln-table>
        </div>
        <div class="col-12 row fl-mb-md">
          <div class="col-2">出库原因</div>
          <div class="col-10" style="color: #c2c2c2">
            {{ state.dialogInitiateData.remark }}
          </div>
        </div>
        <div class="col-12 row fl-mb-md">
          <div class="col-2">快递单号</div>
          <div class="col-10">
            <n-input
              v-model:value="state.dialogInitiateData.trackingNo"
              placeholder="请输入快递单号"
            />
          </div>
        </div>
        <div class="col-12 row fl-mb-md">
          <div class="col-2">退画原因</div>
          <div class="col-10">
            <n-input
              v-model:value="state.dialogInitiateData.returnReason"
              type="textarea"
              placeholder="请输入退画原因"
              :maxlength="800"
            />
          </div>
        </div>
        <div class="col-12 row justify-center">
          <n-button
            tertiary
            class="fl-mr-md"
            style="width: 161px; background: #c7c7c9; color: #ffffff"
            @click="handleDialogInitiateCancel"
            >取消</n-button
          >
          <n-button
            
            type="primary"
            style="width: 161px; color: #fff"
            @click="handleDialogInitiateConfirm"
            :loading="state.btnLoading"
            >确认发起</n-button
          >
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup>
import flnTable from "@/components/flnlayout/table/flntable.vue";
import { Local } from "@/utils/storage.js";
import {
  ref,
  reactive,
  onBeforeMount,
  onMounted,
  getCurrentInstance,
  computed,
} from "vue";
import { settingConfig } from "@/config/settings/index.js";

// 计算属性：获取主题色
const themeColor = computed(() => settingConfig.themeColor);
import { processError, processSuccess } from "@/utils/helper/message";
import { useRouter } from "vue-router";
const router = useRouter();
const currentInstance = getCurrentInstance();
const { $request, $hadRule } =
  currentInstance.appContext.config.globalProperties;
import { NTooltip } from "naive-ui";
import { NButton, NPopover } from "naive-ui";
import ExpressInfo from "./expressinfo.vue";
import StatusInfo from "./statusinfo.vue";
import { set } from "@vueuse/core";
const state = reactive({
  btnLoading: false,
  dialogAddOne: false,
  dialogAddOneData: {
    trackingNo: "",
    groupId: "",
    artworkUid: [],
    courierType: 2,
  },
  dialogInitiate: false,
  dialogInitiateData: {
    trackingNo: "",
    returnReason: "",
    remark: "退还画家",
  },
  tableConfig: {
    rowKey: "groupId",
    refreshCount: 0,
    refreshCountWithPagination: 0,
    listUrl: {
      resDataField: "Data",
      url: "api/returnArtwork/artistReturnStat/query",
      params: [],
    },
    searchConfig: [
      {
        type: "text",
        label: "画家姓名",
        field: "artistName",
      },
      {
        type: "select",
        label: "状态",
        field: "mailStatus",
        config: {
          options: [
            {
              label: "待寄出",
              value: 1,
            },
            {
              label: "已寄出",
              value: 2,
            },
            {
              label: "已签收",
              value: 3,
            },
          ],
        },
      },
    ],
    columns: [
      {
        type: "select",
        width: 100,
        title: "状态",
        field: "mailStatus",
        config: {
          options: [
            {
              label: "待寄出",
              value: 1,
              class: "color-danger",
            },
            {
              label: "已寄出",
              value: 2,
              class: "color-primary",
            },
            {
              label: "已签收",
              value: 3,
              class: "color-info",
            },
          ],
        },
      },
      {
        title: "画家姓名",
        field: "artistName",
      },
      {
        type: "select",
        title: "是否大师",
        field: "isMaster",
        config: {
          options: [
            {
              label: "是",
              value: 1,
            },
            {
              label: "否",
              value: 2,
            },
          ],
        },
      },
      {
        title: "画家编号",
        field: "tnum",
      },
      {
        title: "笔名",
        field: "penName",
      },
      {
        title: "身份证号",
        field: "idNum",
      },
      {
        width: 120,
        title: "收件信息",
        align: "center",
        render(row) {
          if (row.addressConfirm === 1) {
            return h("div", {}, "待画家短信确认");
          } else {
            return h("div", { class: "row items-center justify-center" }, [
              h(
                NTooltip,
                { placement: "top", showArrow: false },
                {
                  default: () =>
                    h(
                      "div",
                      {
                        style: {
                          maxWidth: "200px",
                        },
                      },
                      row.address
                    ),
                  trigger: () =>
                    h(
                      "div",
                      {
                        style: {
                          width: "100px",
                        },
                        class: "sf-text-ellipsis",
                      },
                      row.address
                    ),
                }
              ),
            ]);
          }
        },
      },
      {
        title: "需要寄出画作数",
        field: "pendingMailTotal",
      },
      {
        title: "已寄出画作数",
        field: "mailedTotal",
      },
      {
        title: "已确认画作数",
        field: "addressConfirmTotal",
      },
      {
        title: "发起时间",
        field: "latestSendTime",
      },
    ],
    expandConfig: {
      hasSelection: true,
      searchInTable: true,
      rowKey: "ID",
      refreshCount: 0,
      refreshCountWithPagination: 0,
      listUrl: {
        resDataField: "Data",
        url: "api/returnArtwork/viewReturnArtwork/query",
        params: [
          {
            label: "groupId",
            field: "groupId",
          },
        ],
      },
      searchConfig: [
        {
          type: "select",
          labelStyle: "text-align: left",
          label: "状态",
          field: "mailStatus",
          config: {
            options: [
              {
                label: "待寄出",
                value: 1,
              },
              {
                label: "已寄出",
                value: 2,
              },
              {
                label: "已签收",
                value: 3,
              },
            ],
          },
        },
      ],
      columns: [
        {
          label: "状态",
          field: "mailStatus",
          render(row) {
            return h(StatusInfo, {
              fatherData: row,
              field: "mailStatus",
              options: [
                {
                  label: "待寄出",
                  value: 1,
                  class: "color-danger",
                },
                {
                  label: "已寄出",
                  value: 2,
                  class: "color-primary",
                },
                {
                  label: "已签收",
                  value: 3,
                  class: "color-info",
                },
              ],
            });
          },
        },
        {
          label: "画作名称",
          field: "artworkName",
        },
        {
          label: "画作编号",
          field: "tfnum",
        },
        {
          type: "select",
          label: "画作类型",
          field: "artworkType",
          config: {
            options: [
              {
                label: "优秀画作",
                value: 1,
              },
              {
                label: "赠画",
                value: 2,
              },
              {
                label: "卷轴",
                value: 3,
              },
              {
                label: "普通画作",
                value: 4,
              },
            ],
          },
        },
        {
          label: "长度",
          field: "length",
        },
        {
          label: "宽度",
          field: "width",
        },
        {
          label: "平尺数",
          field: "ruler",
        },
        { type: "image", label: "画作高清图", field: "hdPic" },
        { type: "image", label: "画家画作合影", field: "artistPhoto" },
        { type: "image", label: "画作落款印章处细节图", field: "sealpic" },
        {
          type: "select",
          label: "国展",
          field: "nationalExhibition",
          config: {
            options: [
              {
                label: "无",
                value: 1,
              },
              {
                label: "入围",
                value: 2,
              },
              {
                label: "入选",
                value: 3,
              },
              {
                label: "入围+入选",
                value: 4,
              },
            ],
          },
        },
        { type: "image", label: "入选凭证", field: "nationalExhibitionProof" },
        {
          label: "发起时间",
          field: "sendTime",
        },
        {
          width: 140,
          label: "快递信息",
          render(row) {
            return h(
              NPopover,
              {
                trigger: "click",
                placement: "left",
              },
              {
                trigger: () =>
                  h(
                    "span",
                    {
                      style: {
                        color: themeColor.value,
                        cursor: "pointer",
                        padding: "10px 15px",
                      },
                    },
                    row.trackingNo
                      ? row.latestCourierDesc + " " + row.latestCourierTime
                      : "添加快递信息"
                  ),
                default: () =>
                  h(ExpressInfo, {
                    fatherData: row,
                    onTriggerExpressInfoClick: (e) =>
                      triggerExpressInfoClick(e),
                  }),
              }
            );
          },
        },
      ],
      tableBatchActionsStyle: "margin-left:auto;margin-right:0 !important;",
      tableBatchActions: [
        {
          actionType: "addByOne",
          style: `color:${themeColor.value}`,
          label: "一键添加快递信息",
        },
      ],
    },
  },
  selectedRows: [],
  initiateConfig: { 
    defaultSelectedRows: [],
    rowKey: "artworkUid",
    hasSelection: true,
    refreshCount: 0,
    listUrl: {
      resDataField: "Data",
      url: "api/returnArtwork/canreturn/query",
      params: [],
    },
    searchConfig: [
      {
        type: "selectsearch",
        label: "画家姓名",
        field: "artistUid",
        optionConfig: {
          url: "artist/idname",
          labelField: "Name",
          valueField: "Uuid",
          labelSecondField: "Tnum",
        },
      },
    ],
    columns: [
      { type: "tooltip", title: "画作名称", field: "artworkName" },
      {
        title: "画作编号",
        field: "tfnum",
      },
      {
        type: "select",
        label: "画作类型",
        field: "artworkType",
        config: {
          options: [
            {
              label: "优秀画作",
              value: 1,
            },
            {
              label: "赠画",
              value: 2,
            },
            {
              label: "卷轴",
              value: 3,
            },
            {
              label: "普通画作",
              value: 4,
            },
          ],
        },
      },
      {
        title: "长度",
        field: "length",
      },
      {
        title: "宽度",
        field: "width",
      },
      {
        title: "平尺数",
        field: "ruler",
      },
      { type: "image", label: "画作高清图", field: "hdPic" },
      { type: "image", label: "画家画作合影", field: "artistPhoto" },
      { type: "image", label: "画作落款印章处细节图", field: "sealpic" },
      {
        type: "select",
        label: "国展",
        field: "nationalExhibition",
        config: {
          options: [
            {
              label: "无",
              value: 1,
            },
            {
              label: "入围",
              value: 2,
            },
            {
              label: "入选",
              value: 3,
            },
            {
              label: "入围+入选",
              value: 4,
            },
          ],
        },
      },
      { type: "image", label: "入选凭证", field: "nationalExhibitionProof" },
    ],
  },
});
onBeforeMount(() => {});
onMounted(() => {});

const handleRowActions = ({ btnConfig, rowData }) => {};
const handleBatchActions = ({ btnConfig, selectedRows, fatherData }) => {
  if (btnConfig.actionType === "addByOne") {
    state.dialogAddOneData.trackingNo = "";
    state.dialogAddOneData.artworkUid = selectedRows.map(
      (item) => item.artworkUid
    );
    state.dialogAddOneData.groupId = fatherData.groupId;
    state.dialogAddOne = true;
  }
};
const handleDialogAddOneConfirm = () => {
  state.btnLoading = true;
  let url = "api/mailArtwork/courierEdit";
  let params = state.dialogAddOneData;
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      state.btnLoading = false;
      if (res.status === 0) {
        state.dialogAddOne = false;
        state.tableConfig.refreshCountWithPagination++;
        state.tableConfig.expandConfig.refreshCountWithPagination++;
      } else {
        processError(res.msg || "操作失败！");
      }
    },
    () => {
      state.btnLoading = false;
      processError("操作失败！");
    },
    () => {
      processError("操作失败！");
    }
  );
};
// 发起
const handleInitiate = () => {
  state.selectedRows = [];
  state.dialogInitiateData.trackingNo = "";
  state.dialogInitiateData.returnReason = "";
  state.dialogInitiate = true;
};
const handleDialogInitiateCancel = () => {
  state.dialogInitiate = false;
  state.initiateConfig.defaultSelectedRows = [];
};
const handleDialogInitiateConfirm = () => {
  if (state.selectedRows.length === 0) {
    processError("请选择画作！");
    return;
  }
  state.btnLoading = true;
  let url = "api/mailArtwork/confirm";
  let params = {
    artworkUid: state.selectedRows.map((item) => item.artworkUid),
    courierType: 2,
    remark: state.dialogInitiateData.remark,
    trackingNo: state.dialogInitiateData.trackingNo,
    returnReason: state.dialogInitiateData.returnReason,
  };
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      state.btnLoading = false;
      if (res.status === 0) {
        processSuccess("操作成功！");
        setTimeout(() => {
          state.initiateConfig.defaultSelectedRows = [];
          state.dialogInitiate = false;
          state.tableConfig.refreshCount++;
          state.tableConfig.expandConfig.refreshCount++;
        }, 500);
      } else {
        processError(res.msg || "操作失败！");
      }
    },
    () => {
      state.btnLoading = false;
      processError("操作失败！");
    },
    () => {
      processError("操作失败！");
    }
  );
};
const handleTableSelectCheck = (data) => {
  if (data && Array.isArray(data.selectedRow)) {
    data.selectedRow = data.selectedRow.filter((item) => {
      if (item) {
        return item;
      }
    });
  }
  if (data.action === "check" || data.action === "checkAll") {
    state.selectedRows = state.selectedRows.concat(data.selectedRow);
    state.selectedRows = state.selectedRows.filter((item, index, arr) => {
      return (
        arr.findIndex((obj) => JSON.stringify(obj) === JSON.stringify(item)) ===
        index
      );
    });
  }
  if (data.action === "uncheck") {
    state.selectedRows = state.selectedRows.filter((item) => {
      return item.artworkUid !== data.selectedRow.artworkUid;
    });
  }
  if (data.action === "uncheckAll") {
    state.selectedRows = state.selectedRows.filter((item) => {
      return (
        data.selectedRow.findIndex((obj) => {
          return obj.artworkUid === item.artworkUid;
        }) === -1
      );
    });
  }
  state.initiateConfig.defaultSelectedRows = state.selectedRows;
};
// 快递信息编辑处理
const triggerExpressInfoClick = (e) => {
  state.tableConfig.refreshCountWithPagination++;
  state.tableConfig.expandConfig.refreshCountWithPagination++;
  state.selectedRows = [];
};
</script>

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