<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="80%"
    :visible="visible"
    :confirm-loading="loading"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑菜品' : '发布菜品'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-spin :spinning="loading">
      <a-space :size="16" style="margin-bottom: 30px">
        <a-space v-if="!isUpdate">
          <a-radio-group v-model:value="form.type">
            <a-radio-button value="single">发布一天</a-radio-button>
            <a-radio-button value="multiple" disabled="">发布多天</a-radio-button>
          </a-radio-group>
        </a-space>
        <a-space v-if="form.type === 'single'">
          <span class="ele-text-secondary">发布日期</span>
          <a-date-picker
            placeholder="发布日期"
            value-format="YYYY-MM-DD"
            :disabled="isUpdate"
            v-model:value="form.dayTime"
          />
        </a-space>
        <a-space v-if="form.type === 'multiple'" :size="16">
          <a-range-picker
            v-model:value="dateRange"
            value-format="YYYY-MM-DD"
            class="ele-fluid"
          />
          <a-radio-group v-model:value="form.isRepeat">
            <a-radio :value="1">多天菜品重复</a-radio>
            <a-radio :value="2">多天菜品不重复</a-radio>
          </a-radio-group>
        </a-space>
        <a-space>
          <span class="ele-text-secondary">使用往日菜单</span>
          <a-date-picker
            placeholder="选择往日菜单"
            value-format="YYYY-MM-DD"
            v-model:value="form.oldTime"
            @change="selectOldTime"
          />
        </a-space>
      </a-space>
<!--      <a-divider style="margin: 12px 0 12px 0" />-->
<!--      <div>{{ targetKeys1 }}</div>-->
<!--      <div>{{ targetKeys2 }}</div>-->
<!--      <div>{{ targetKeys3 }}</div>-->
<!--      <div>{{ selectedGoodsIds }}</div>-->
      <div
        style="background-color: #f3f3f3; padding: 8px;">
        <a-form
          :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
          :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
        >
          <a-row type="flex" :gutter="8" justify="space-around">
            <a-col :md="8" :sm="24" :xs="24">
              <a-card title="早餐" :bordered="false">
                <a-transfer
                  v-model:target-keys="targetKeys1"
                  v-model:selected-keys="selectedKeys1"
                  :data-source="breakfast"
                  :list-style="{
                    width: '250px',
                    height: '500px',
                  }"
                  :titles="['菜品', '已选']"
                  :render="item => item.title"
                  :disabled="disabled"
                  @selectChange="onChange1"
                />
              </a-card>
            </a-col>
            <a-col :md="8" :sm="24" :xs="24">
              <a-card title="午餐" :bordered="false">
                <a-transfer
                  v-model:target-keys="targetKeys2"
                  v-model:selected-keys="selectedKeys2"
                  :data-source="lunch"
                  :list-style="{
                    width: '250px',
                    height: '500px',
                  }"
                  :titles="['菜品', '已选']"
                  :render="item => item.title"
                  :disabled="disabled"
                  @selectChange="onChange2"
                />
              </a-card>
            </a-col>
            <a-col :md="8" :sm="24" :xs="24">
              <a-card title="晚餐" :bordered="false">
                <a-transfer
                  v-model:target-keys="targetKeys3"
                  v-model:selected-keys="selectedKeys3"
                  :data-source="dinner"
                  :list-style="{
                    width: '250px',
                    height: '500px',
                  }"
                  :titles="['菜品', '已选']"
                  :render="item => item.title"
                  :disabled="disabled"
                  @selectChange="onChange3"
                />
              </a-card>
            </a-col>
          </a-row>
        </a-form>
      </div>

    </a-spin>
  </ele-modal>
</template>

<script lang="ts" setup>
  import {ref, reactive, watch, computed} from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, toDateString } from "ele-admin-pro";
  import { addBCPlan, updateBCPlan, listBCPlan } from '@/api/apps/bc/plan';
  import type { Customer } from '@/api/oa/customer/model';
  import { useUserStore } from '@/store/modules/user';
  import { pageGoods } from "@/api/goods";
  import { BCPlan } from "@/api/apps/bc/plan/model";

  const userStore = useUserStore();
  // 当前用户信息
  const loginUser = computed(() => userStore.info ?? {});
  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Customer | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 当期时间
  const dayTime = toDateString(new Date());
  // 类型 single|multiple
  // const type = ref<string>('single');
  // 日期范围选择
  const dateRange = ref<[string, string]>(['', '']);

  // 穿梭框数据
  const breakfast = ref<any[]>();
  const targetKeys1 = ref<any[]>([]);
  const selectedKeys1 =ref<any[]>();
  const lunch = ref<any[]>();
  const targetKeys2 = ref<any[]>([]);
  const selectedKeys2 =ref<any[]>();
  const dinner = ref<any[]>();
  const targetKeys3 = ref<any[]>([]);
  const selectedKeys3 =ref<any[]>();
  const selectedGoodsIds = ref<any[]>([]);

  // 合并选中的菜品
  const onChange1 = () => {
    selectedGoodsIds.value = [...targetKeys1.value,...targetKeys2.value,...targetKeys3.value]
  }
  const onChange2 = () => {
    selectedGoodsIds.value = [...targetKeys1.value,...targetKeys2.value,...targetKeys3.value]
  }
  const onChange3 = () => {
    selectedGoodsIds.value = [...targetKeys1.value,...targetKeys2.value,...targetKeys3.value]
  }

  // 选择往日菜单
  const selectOldTime = (date) => {
    form.oldTime = date
    listBCPlan({oldTime: toDateString(form.oldTime, 'YYYY-MM-DD HH:mm:ss')}).then(data => {
      if(data[0]){
        selectedGoodsIds.value = JSON.parse(data[0].goodsIds);
        reload();
        message.success('加载成功');
      }else{
        message.info('当天没有发布数据')
      }
    })
  }

  // 用户信息
  const form = reactive<BCPlan>({
    type: 'single',
    bcPlanId: undefined,
    isRepeat: 1,
    period: '',
    dayTime: toDateString(new Date(),'YYYY-MM-DD'),
    oldTime: '',
    goodsIds: '',
    comments: '',
    status: 1
  });

  // 已上传数据, 可赋初始值用于回显
  const images = ref(<any>[]);

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    customerName: [
      {
        required: true,
        type: 'string',
        message: '请输入订单名称',
        trigger: 'blur'
      }
    ],
    customerCode: [
      {
        required: true,
        type: 'string',
        message: '请输入合法的IP地址',
        trigger: 'blur'
      }
    ],
    progress: [
      {
        required: true,
        type: 'string',
        message: '请选择跟进状态',
        trigger: 'blur'
      }
    ]
  });

  const { resetFields, validate, validateInfos } = useForm(form, rules);

  /* 保存编辑 */
  const save = () => {
    validate()
      .then(() => {
        loading.value = true;
        // 去除空格
        // form.customerName = form.customerName?.replace(/\s*/g, '');
        // const data = {
        //   ...form
        // };
        // 转字符串

        form.userId = loginUser.value.userId;
        form.goodsIds = JSON.stringify(selectedGoodsIds.value)
        form.dayTime = toDateString(form.dayTime, 'YYYY-MM-DD HH:mm:ss');
        form.period = (targetKeys1.value.length > 0 ? '早餐 ' : '') + (targetKeys2.value.length > 0 ? '午餐 ' : '') + (targetKeys3.value.length > 0 ? '晚餐' : '');
        const saveOrUpdate = isUpdate.value ? updateBCPlan : addBCPlan;
        saveOrUpdate(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  const reload = () => {
    loading.value = true;
    pageGoods({limit:100}).then(data => {
      targetKeys1.value = []
      targetKeys2.value = []
      targetKeys3.value = []
      breakfast.value = data?.list.filter(d => d.categoryId == 25).map(d => {
        // 处理编辑状态下是否选中
        if(selectedGoodsIds.value.indexOf(d.goodsId) > -1){
          targetKeys1.value.push(d.goodsId);
        }
        return {
          key: d.goodsId,
          title: d.goodsName
        }
      })
      lunch.value = data?.list.filter(d => d.categoryId == 26).map(d => {
        // 处理编辑状态下是否选中
        if(selectedGoodsIds.value.indexOf(d.goodsId) > -1){
          targetKeys2.value.push(d.goodsId);
        }
        return {
          key: d.goodsId,
          title: d.goodsName
        }
      })
      dinner.value = data?.list.filter(d => d.categoryId == 27).map(d => {
        // 处理编辑状态下是否选中
        if(selectedGoodsIds.value.indexOf(d.goodsId) > -1){
          targetKeys3.value.push(d.goodsId);
        }
        return {
          key: d.goodsId,
          title: d.goodsName
        }
      })
      loading.value = false;
    })
  }

  reload();

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignObject(form, props.data);
          selectedGoodsIds.value = JSON.parse(form.goodsIds);
          reload();
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less"></style>
