<template>
  <el-container class="send">
    <el-main>
      <el-tabs class="sa-m-b-20" v-model="state.dispatch_type">
        <el-tab-pane v-if="state.nosendItem.length" label="快递发货" name="express"></el-tab-pane>
        <el-tab-pane v-if="state.customItem.length" label="手动发货" name="custom"></el-tab-pane>
      </el-tabs>
      <el-alert class="sa-alert sa-m-b-16">
        <template #title>温馨提示：如果该商品处在售后状态，请先处理完售后再进行发货。</template>
      </el-alert>
      <div v-if="state.dispatch_type == 'express'">
        <el-table
          ref="expressTableRef"
          class="sa-table"
          :data="state.nosendItem"
          @selection-change="handleSelectionChange"
        >
          <template #empty>
            <sa-empty />
          </template>
          <el-table-column type="selection" width="40" />
          <el-table-column label="商品信息" min-width="360">
            <template #default="scope">
              <div class="sa-flex">
                <sa-image :url="scope.row.goods_image" size="40"></sa-image>
                <div class="sa-m-l-8">{{ scope.row.goods_title }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goods_num" label="数量" min-width="80"></el-table-column>
          <el-table-column prop="dispatch_status_text" label="状态" min-width="140">
            <template #default="scope">
              {{ scope.row.dispatch_status_text }}/{{ scope.row.aftersale_status_text }}
            </template>
          </el-table-column>
          <el-table-column label="快递单号" min-width="80">
            <template #default>-</template>
          </el-table-column>
        </el-table>
        <div class="address">
          <div class="title sa-m-b-16">配送信息</div>
          <div class="sa-m-l-16" v-if="props.modal?.params?.params?.data?.address">
            <div class="sa-flex sa-m-b-8">
              <div class="label">收货信息：</div>
              <div class="content">
                {{ props.modal?.params?.params?.data?.address?.consignee }}&nbsp;
                {{ props.modal?.params?.params?.data?.address?.mobile }}
              </div>
            </div>
            <div class="sa-flex sa-col-top sa-m-b-16">
              <div class="label">收货地址：</div>
              <div class="content">
                <div>
                  {{ props.modal?.params?.params?.data?.address?.province_name }}&nbsp;
                  {{ props.modal?.params?.params?.data?.address?.city_name }}&nbsp;
                  {{ props.modal?.params?.params?.data?.address?.district_name }}
                </div>
                <div>{{ props.modal?.params?.params?.data?.address?.address }}</div>
              </div>
            </div>
          </div>
          <template v-if="!props.modal?.params?.params?.data?.address">{{
            props.modal?.params?.params?.data?.address_id
          }}</template>
        </div>
        <div class="express">
          <div class="title sa-m-b-16">物流信息</div>
          <div class="sa-m-l-16">
            <el-form>
              <el-form-item label="发货方式">
                <el-radio-group v-model="state.method">
                  <el-radio label="input">物流快递</el-radio>
                  <el-radio label="api">一键发货</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
            <el-form
              v-if="state.method == 'input'"
              ref="expressRef"
              :inline="true"
              :model="express"
              :rules="state.method == 'input' ? state.expressRules : {}"
            >
              <el-form-item label="快递公司" prop="code">
                <el-select
                  v-model="express.code"
                  placeholder="请选择快递公司"
                  @change="onChangeExpressCode"
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="remoteMethod"
                  :loading="deliverCompany.loading"
                  autocomplete="none"
                >
                  <el-option
                    v-for="dc in deliverCompany.data"
                    :key="dc"
                    :label="dc.name"
                    :value="dc.code"
                    :ref="`dc-${dc.code}`"
                    :data-name="dc.name"
                    >{{ dc.name }}&nbsp;({{ dc.code }})</el-option
                  >
                  <div class="sa-p-l-15 sa-p-r-27">
                    <sa-pagination
                      layout="total, prev, pager, next"
                      :pageData="deliverCompany.pageData"
                      @updateFn="getDeliverCompany"
                    />
                  </div>
                </el-select>
              </el-form-item>
              <el-form-item label="快递单号" prop="no">
                <el-input v-model="express.no" placeholder="请输入快递单号" />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div v-if="state.dispatch_type == 'custom'">
        <el-table
          ref="customTableRef"
          class="sa-table"
          :data="state.customItem"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="48"></el-table-column>
          <el-table-column label="商品信息" min-width="360">
            <template #default="scope">
              <div class="sa-flex">
                <sa-image :url="scope.row.goods_image" size="40"></sa-image>
                <div class="sa-m-l-8">{{ scope.row.goods_title }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goods_num" label="数量" min-width="80"></el-table-column>
          <el-table-column prop="dispatch_status_text" label="状态" min-width="140">
            <template #default="scope">
              {{ scope.row.dispatch_status_text }}/{{ scope.row.aftersale_status_text }}
            </template>
          </el-table-column>
          <el-table-column label="快递单号" min-width="80">
            <template #default>-</template>
          </el-table-column>
        </el-table>
        <el-form class="sa-m-t-20">
          <el-form-item label="发货类型：">
            <el-radio-group v-model="state.custom_type" @change="onChangeAutosendType">
              <el-radio label="text">固定内容</el-radio>
              <el-radio label="params">自定义内容</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="state.custom_type == 'text'" label="发货内容：">
            <el-input v-model="state.custom_content" placeholder="请输入自动发货内容"></el-input>
          </el-form-item>
          <el-form-item v-if="state.custom_type == 'params'" label="发货内容：">
            <div class="sa-template-wrap">
              <div class="title sa-flex">
                <div class="key">参数名称</div>
                <div class="key">内容</div>
                <div class="oper">操作</div>
              </div>
              <draggable
                v-model="state.custom_content"
                :animation="300"
                handle=".sortable-drag"
                item-key="element"
              >
                <template #item="{ element, index }">
                  <div class="item">
                    <el-form-item class="key">
                      <el-input placeholder="请输入" v-model="element.title"> </el-input>
                    </el-form-item>
                    <el-form-item class="key">
                      <el-input placeholder="请输入" v-model="element.content"> </el-input>
                    </el-form-item>
                    <el-form-item class="oper">
                      <el-popconfirm
                        width="fit-content"
                        confirm-button-text="确认"
                        cancel-button-text="取消"
                        title="确认删除这条记录?"
                        @confirm="onDeleteContent(index)"
                      >
                        <template #reference>
                          <el-button type="danger" link @click.stop>删除 </el-button>
                        </template>
                      </el-popconfirm>
                      <i class="iconfont iconmove sortable-drag"></i>
                    </el-form-item>
                  </div>
                </template>
              </draggable>
              <el-button class="add-params" type="primary" plain icon="Plus" @click="onAddContent"
                >添加
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button
        type="primary"
        :loading="state.sendLoading"
        :disabled="state.expressItem.length == 0 || state.sendLoading"
        @click="onSend"
        >立即发货</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { computed, getCurrentInstance, onMounted, reactive, ref, nextTick, watch } from 'vue';
  import { api } from '../order.service';
  import useExpress from '@/app/shop/admin/data/express/express.js';
  import draggable from 'vuedraggable';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps(['modal']);

  const { proxy } = getCurrentInstance();

  // 表格引用
  const expressTableRef = ref();
  const customTableRef = ref();

  const state = reactive({
    nosendItem: computed(() => {
      if (!props.modal?.params?.params?.data?.items) return [];
      return props.modal.params.params.data.items.filter(
        (i) =>
          (i.dispatch_status == 0 || i.dispatch_status === undefined) &&
          (i.refund_status == 0 || i.refund_status === undefined) &&
          (i.dispatch_type == 'express' || i.dispatch_type === undefined),
      );
    }),
    method: 'input',
    expressItem: [],
    expressRules: {
      code: [{ required: true, message: '请选择', trigger: 'none' }],
      no: [{ required: true, message: '请输入快递单号', trigger: 'none' }],
    },
    sendLoading: false,

    dispatch_type: 'express',
    customItem: computed(() => {
      if (!props.modal?.params?.params?.data?.items) return [];
      return props.modal.params.params.data.items.filter(
        (i) =>
          (i.dispatch_status == 0 || i.dispatch_status === undefined) &&
          (i.refund_status == 0 || i.refund_status === undefined) &&
          i.dispatch_type == 'custom',
      );
    }),
    custom_type: 'text',
    custom_content: [],
  });

  function handleSelectionChange(val) {
    state.expressItem = val;
  }

  const { express, deliverCompany, getDeliverCompany, onChangeExpressCode, remoteMethod } =
    useExpress();
  // TODO
  async function onSend() {
    let order_item_ids = [];
    state.expressItem.forEach((item) => {
      order_item_ids.push(item.id);
    });
    if (state.dispatch_type == 'express') {
      if (state.method == 'input') {
        proxy.$refs.expressRef &&
          proxy.$refs.expressRef.validate(async (valid) => {
            if (valid) {
              state.sendLoading = true;
              const { error } = await api.order.dispatch({
                order_id: props.modal?.params?.params?.data?.id,
                order_item_ids,
                action: 'confirm',
                method: 'input',
                express: express,
              });
              state.sendLoading = false;
              if (error == 0) {
                emit('modalCallBack', { event: 'confirm' });
              }
            }
          });
      } else if (state.method == 'api') {
        state.sendLoading = true;
        const { error } = await api.order.dispatch({
          order_id: props.modal?.params?.params?.data?.id,
          order_item_ids,
          action: 'confirm',
          method: 'api',
        });
        state.sendLoading = false;
        if (error == 0) {
          emit('modalCallBack', { event: 'confirm' });
        }
      }
    } else if (state.dispatch_type == 'custom') {
      const { error } = await api.order.customDispatch({
        order_id: props.modal?.params?.params?.data?.id,
        order_item_ids,
        custom_type: state.custom_type,
        custom_content: state.custom_content,
      });
      state.sendLoading = false;
      if (error == 0) {
        emit('modalCallBack', { event: 'confirm' });
      }
    }
  }

  function onChangeAutosendType(type) {
    state.custom_content = type == 'text' ? '' : [];
  }
  function onAddContent() {
    if (!state.custom_content) {
      state.custom_content = [];
    }
    state.custom_content.push({
      title: '',
      content: '',
    });
  }
  function onDeleteContent(index) {
    state.custom_content.splice(index, 1);
  }

  // 监听发货类型变化，自动选中所有商品
  watch(
    () => state.dispatch_type,
    (newType) => {
      nextTick(() => {
        if (newType === 'express' && expressTableRef.value && state.nosendItem.length) {
          state.nosendItem.forEach((row) => {
            expressTableRef.value.toggleRowSelection(row, true);
          });
        } else if (newType === 'custom' && customTableRef.value && state.customItem.length) {
          state.customItem.forEach((row) => {
            customTableRef.value.toggleRowSelection(row, true);
          });
        }
      });
    },
  );

  onMounted(() => {
    if (state.nosendItem.length) {
      state.dispatch_type = 'express';
      // 默认选中所有快递发货商品
      nextTick(() => {
        if (expressTableRef.value) {
          state.nosendItem.forEach((row) => {
            expressTableRef.value.toggleRowSelection(row, true);
          });
        }
      });
    } else if (state.customItem.length) {
      state.dispatch_type = 'custom';
      // 默认选中所有手动发货商品
      nextTick(() => {
        if (customTableRef.value) {
          state.customItem.forEach((row) => {
            customTableRef.value.toggleRowSelection(row, true);
          });
        }
      });
    }
  });
</script>
<style lang="scss" scoped>
  .send {
    .address,
    .express {
      line-height: 16px;
      font-size: 12px;
      font-weight: 400;
      .title {
        height: 32px;
        line-height: 32px;
        padding: 0 16px;
        background: var(--sa-table-header-bg);
        border-radius: 4px;
        font-size: 12px;
        font-weight: 400;
        color: var(--sa-subtitle);
      }
      .label {
        color: var(--sa-subfont);
      }
      .content {
        color: var(--sa-subtitle);
      }
    }
  }
</style>
