import { defineComponent, onMounted, reactive } from 'vue';
import styles from './operation.module.less';
import MHeader from '@/components/m-header';
import {
  Button,
  Cell,
  CellGroup,
  DatePicker,
  Field,
  Icon,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  Tag,
  showToast
} from 'vant';
import { activityStatus, programType } from '@/helpers/constant';
import MUploader from '@/components/m-uploader';
import MUploaderInside from '@/components/m-uploader/inside';
import iconVideo from './images/icon-video.png';
import iconDelete from './images/icon-delete.png';
import iconUploadImg from '../patrol-evaluation/images/icon-upload-img.png';
import iconUploadVideo from '../patrol-evaluation/images/icon-upload-video.png';
import MSticky from '@/components/m-sticky';
import { formatterDatePicker, toChinesNum } from '@/helpers/utils';
import request from '@/helpers/request';
import InputTimer from './components/input-timer';
import PerformanceTeam from './components/performance-team';
import MPopup from '@/components/m-popup';
import CastModal from './components/cast-modal';
import dayjs from 'dayjs';
import { useRoute, useRouter } from 'vue-router';
import { checkFile } from '@/helpers/toolsValidate';

type detailItemType = {
  id: string | number | null;
  name: string;
  type: string;
  musicGroupId: string | null;
  musicGroupName: string | null;
  subjectAllList: any[];
  subjectIdList: any[];
  time: number | null;
  performerList: any[];
  attachmentUrl: string[];
  attachmentVideoUrl: string[];
  attachmentImgUrl: string[];
};

const detailItem: detailItemType = {
  id: null,
  name: '',
  type: '', // 节目类型
  musicGroupId: null, // 表演乐团
  musicGroupName: null, //
  subjectAllList: [] as any, // 表演团队数据列表
  subjectIdList: [] as any, // 表演团队
  time: null, // 表演时间
  performerList: [], // 演员列表
  attachmentUrl: [] as string[],
  attachmentVideoUrl: [] as string[], // 视频目录
  attachmentImgUrl: [] as string[]
};

// 格式化时间
export const formatterTimer = (timer: number) => {
  if (!timer) {
    return {
      minute: null,
      secord: null
    };
  } else {
    const minute = Math.floor(timer / 60);
    const secord = timer % 60;
    return {
      minute,
      secord
    };
  }
};

export default defineComponent({
  name: 'operation-page',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const forms = reactive({
      activityDetailId: route.query.id, // 活动编号
      timerStatus: false,
      currentDate: [
        dayjs().format('YYYY'),
        dayjs().format('MM'),
        dayjs().format('DD')
      ] as any,
      orchestraStatus: false, // 乐团列表状态
      orchestraColumns: [] as any,
      programType: '',
      programTimerStatus: false, // 节目时长状态
      deleteStatus: false, // 删除弹窗
      teamStatus: false, // 表演团队状态
      castStatus: false, // 学员名称状态
      selectOrchestra: [] as any, // 选中的乐团
      // selectOrchestraIndex: 0, // index
      deleteIndex: 0, // 删除的编号

      startTime: dayjs().format('YYYY-MM-DD'),
      name: '',
      type: '',
      detail: [{ ...detailItem }]
    });

    // 乐团列表
    const musicGroupPage = async () => {
      try {
        const { data } = await request.get(
          '/api-web/cooperationOrgan/musicGroupPage'
        );
        (data || []).forEach((item: any) => {
          forms.orchestraColumns.push({
            text: item.name,
            value: item.id
          });
        });
      } catch {
        //
      }
    };

    // 获取表演团队和演员
    const getUserList = async () => {
      try {
        const { data } = await request.post(
          '/api-web/schoolActivity/userList',
          {
            data: {
              activityDetailId: forms.activityDetailId,
              musicGroupId: forms.selectOrchestra.musicGroupId,
              subjectIds: []
            }
          }
        );
        const tempData = data || [];
        forms.selectOrchestra.subjectAllList = tempData;
        forms.selectOrchestra.performerList = tempData;

        // 添加默认选中的编号
        forms.selectOrchestra.subjectIdList = [];
        tempData.forEach((item: any) => {
          forms.selectOrchestra.subjectIdList.push(item.subjectId);
        });
      } catch {
        //
      }
    };

    // 添加节目
    const onAddItem = () => {
      forms.detail.push({ ...detailItem });
    };

    // 删除节目
    const onDelete = (index: number) => {
      if (forms.detail.length <= 1) return;
      forms.deleteIndex = index;
      forms.deleteStatus = true;
    };

    // 格式化员工数量
    const formatterStudents = (list: any) => {
      let count = 0;
      list.forEach((item: any) => {
        count += item.studentCount;
      });
      return count;
    };

    // 格式化选中的演员
    const formatterPerformer = (ids: any[]) => {
      const tempList: any = [];
      // 先从默认选中的数据中取
      forms.selectOrchestra.performerList?.forEach((item: any) => {
        if (ids.includes(item.subjectId)) tempList.push(item);
      });
      // 在从总的里面取
      forms.selectOrchestra.subjectAllList?.forEach((item: any) => {
        const tmpPerformanceIndex =
          forms.selectOrchestra.performerList?.findIndex(
            (p: any) => p.subjectId == item.subjectId
          );
        if (ids.includes(item.subjectId) && tmpPerformanceIndex < 0) {
          tempList.push(item);
        }
      });
      forms.selectOrchestra.performerList = tempList;
    };

    // 初始化已经先中的学生
    const formatterStudentList = (list: any[]) => {
      const tempList: any[] = [];
      list.map((student: any) => {
        let count = 0;
        const students: any[] = [];

        student.studentList.forEach((item: any) => {
          if (item.selected) {
            count++;
            students.push(item);
          }
        });

        if (count > 0) {
          tempList.push({
            studentCount: students.length,
            subjectId: student.subjectId,
            subjectName: student.subjectName,
            studentList: students
          });
        }
      });

      return tempList || [];
    };

    const getDetail = async () => {
      try {
        const { data } = await request.get(
          '/api-web/schoolActivity/detail/' + forms.activityDetailId
        );
        const { detail, name, startTime, type } = data || {};

        // startTime: forms.startTime,
        //   endTime: forms.startTime + ' 23:59:59',
        //   name: forms.name,
        //   type: forms.type,
        //   detail: [] as any[]
        forms.startTime = dayjs(startTime).format('YYYY-MM-DD');
        forms.name = name;
        forms.type = type;

        forms.currentDate = [
          dayjs(startTime).format('YYYY'),
          dayjs(startTime).format('MM'),
          dayjs(startTime).format('DD')
        ];
        const initDetails: any[] = [];

        detail.forEach((item: any) => {
          const url: string[] = item.attachmentUrl
            ? item.attachmentUrl.split(',')
            : [];
          const videoUrl: string[] = [];
          const imgUrl: string[] = [];
          url.forEach((url: string) => {
            if (checkFile(url, 'image')) {
              imgUrl.push(url);
            } else {
              videoUrl.push(url);
            }
          });
          const tmp: any = {
            id: item.id,
            name: item.name,
            type: item.type,
            musicGroupId: item.musicGroupId,
            musicGroupName: item.musicGroupName,
            subjectAllList: item.studentList,
            subjectIdList: item.subjectIdList
              ? item.subjectIdList.split(',').map((i: any) => Number(i))
              : [],
            time: item.time,
            performerList: formatterStudentList(item.studentList),
            attachmentUrl: url,
            attachmentVideoUrl: videoUrl,
            attachmentImgUrl: imgUrl
          };
          initDetails.push(tmp);
        });
        forms.detail = initDetails;
      } catch {
        //
      }
    };

    onMounted(() => {
      musicGroupPage();

      if (forms.activityDetailId) {
        getDetail();
      }
    });

    const checkForms = () => {
      if (!forms.name.trim()) {
        showToast('请填写活动名称');
        return false;
      }
      if (forms.name.length < 3 || forms.name.length > 15) {
        showToast('活动名称长度3~15');
        return false;
      }
      if (!forms.type) {
        showToast('请选择活动类别');
        return false;
      }

      for (let i = 0, j = forms.detail.length; i < j; i++) {
        const tDetail = forms.detail[i];
        if (!tDetail.name.trim()) {
          showToast('节目名称不能为空');
          return false;
        }
        if (!tDetail.type) {
          showToast('请选择节目类型');
          return false;
        }
        if (!tDetail.musicGroupId) {
          showToast('请选择表演乐团');
          return false;
        }
        if (tDetail.subjectIdList.length <= 0) {
          showToast('请选择表演团队');
          return false;
        }

        if (formatterStudents(tDetail.performerList) <= 0) {
          showToast('请选择演员');
          return false;
        }
        if (!tDetail.time) {
          showToast('请输入节目时长');
          return;
        }
      }

      return true;
    };
    const onSubmit = async () => {
      try {
        // 校验
        if (!checkForms()) return;

        const params = {
          id: forms.activityDetailId || null,
          startTime: forms.startTime,
          endTime: forms.startTime + ' 23:59:59',
          name: forms.name.trim(),
          type: forms.type,
          detail: [] as any[]
        };
        const tempDetail: any[] = [];
        forms.detail.forEach((item: any, index: number) => {
          console.log(item);
          tempDetail.push({
            id: item.id || null,
            sort: index + 1,
            name: item.name.trim(),
            type: item.type,
            musicGroupId: item.musicGroupId + '',
            subjectIdList: item.subjectIdList.join(','),
            studentNum: formatterStudents(item.performerList),
            studentList: item.performerList,
            time: item.time,
            attachmentUrl: [
              ...item.attachmentImgUrl,
              ...item.attachmentVideoUrl
            ].join(',')
          });
        });
        params.detail = tempDetail;

        if (forms.activityDetailId) {
          await request.post('/api-web/schoolActivity/update', {
            hideLoading: false,
            data: params
          });
        } else {
          await request.post('/api-web/schoolActivity/save', {
            hideLoading: false,
            data: params
          });
        }

        // router.push('/activity-record');
        router.back();
      } catch {
        //
      }
    };
    return () => (
      <div class={styles.operation}>
        <MHeader title={forms.activityDetailId ? '编辑活动' : '新增活动'} />

        <CellGroup inset class={styles.topCellGroup}>
          <Field
            isLink
            label="活动日期"
            inputAlign="right"
            readonly
            clearable={false}
            v-model={forms.startTime}
            onClick={() => (forms.timerStatus = true)}
            placeholder="请选择活动日期"></Field>
          <Field
            label="活动名称"
            inputAlign="right"
            placeholder="请填写活动名称"
            maxlength={15}
            v-model={forms.name}
            autocomplete="off"
          />
          <Field label="活动类别" labelAlign="top">
            {{
              input: () => (
                <RadioGroup class={styles.searchTypeFlex} v-model={forms.type}>
                  {Object.keys(activityStatus).map((item: string) => (
                    <Tag
                      type={forms.type === item ? 'primary' : 'default'}
                      round>
                      <Radio name={item} />
                      {activityStatus[item]}
                    </Tag>
                  ))}
                </RadioGroup>
              )
            }}
          </Field>
        </CellGroup>

        {forms.detail.map((item: any, index: number) => (
          <CellGroup inset class={styles.topCellGroup}>
            <Cell center>
              {{
                icon: () => <Icon name={iconVideo} class={styles.iconImg} />,
                title: () => (
                  <div class={styles.topTitle}>
                    节目{toChinesNum(index + 1)}
                  </div>
                ),
                value: () => (
                  <Icon
                    name={iconDelete}
                    class={[
                      styles.iconImg,
                      forms.detail.length <= 1 ? styles.disabled : ''
                    ]}
                    onClick={() => onDelete(index)}
                  />
                )
              }}
            </Cell>
            <Field
              label="节目名称"
              inputAlign="right"
              placeholder="请填写节目名称"
              maxlength={10}
              v-model={item.name}
              autocomplete="off"
            />
            <Field
              label="节目类型"
              inputAlign="right"
              placeholder="请填写节目"
              class={styles.programType}>
              {{
                input: () => (
                  <RadioGroup
                    class={[styles.searchTypeFlex, styles.small]}
                    v-model={item.type}>
                    {Object.keys(programType).map((program: string) => (
                      <Tag
                        type={item.type === program ? 'primary' : 'default'}
                        round>
                        <Radio name={program} />
                        {programType[program]}
                      </Tag>
                    ))}
                  </RadioGroup>
                )
              }}
            </Field>
            <Field
              isLink
              label="表演乐团"
              inputAlign="right"
              readonly
              clearable={false}
              v-model={item.musicGroupName}
              onClick={() => {
                if (forms.orchestraColumns.length <= 0) {
                  showToast('暂无乐团');
                  return;
                }
                forms.orchestraStatus = true;
                forms.selectOrchestra = [];
                forms.selectOrchestra = item;
              }}
              placeholder="请选择表演乐团"
            />
            <Field
              isLink
              label="表演团队"
              inputAlign="right"
              readonly
              clearable={false}
              onClick={() => {
                if (!item.musicGroupId) {
                  showToast('请选择表演乐团');
                  return;
                }
                forms.teamStatus = true;
                forms.selectOrchestra = [];
                forms.selectOrchestra = item;
              }}
              placeholder={
                item.subjectIdList.length > 0 ? '' : '请选择表演乐团'
              }
              border={item.subjectIdList.length <= 0}
              class={item.subjectIdList.length > 0 ? styles.teamCell : ''}
            />
            {item.subjectIdList.length > 0 && (
              <Cell class={styles.tagCell} center>
                {{
                  title: () =>
                    item.subjectIdList.map(
                      (subjectId: [number, string], index: number) => {
                        let subjectName = '';
                        item.subjectAllList.forEach((subject: any) => {
                          if (subject.subjectId === subjectId) {
                            subjectName = subject.subjectName;
                          }
                        });
                        return (
                          <Tag
                            type="primary"
                            plain
                            class={styles.tagItem}
                            onClick={() => {
                              item.subjectIdList.splice(index, 1);
                              formatterPerformer(item.subjectIdList);
                            }}>
                            {subjectName}
                            <Icon name="cross" class={styles.closeable} />
                          </Tag>
                        );
                      }
                    )
                }}
              </Cell>
            )}

            <Field
              isLink
              label="演员"
              inputAlign="right"
              readonly
              clearable={false}
              onClick={() => {
                if (item.subjectIdList.length <= 0) {
                  showToast('请选择表演团队');
                  return;
                }
                forms.selectOrchestra = [];
                forms.selectOrchestra = item;
                forms.castStatus = true;
              }}
              v-slots={{
                input: () =>
                  formatterStudents(item.performerList) > 0 ? (
                    <div class={styles.performance}>
                      共 <span>{formatterStudents(item.performerList)}</span> 名
                    </div>
                  ) : (
                    <div class={styles.placeholder}>请选择演员</div>
                  )
              }}
            />
            <Field
              label="节目时长"
              inputAlign="right"
              onClick={() => {
                forms.selectOrchestra = [];
                forms.selectOrchestra = item;
                forms.programTimerStatus = true;
              }}
              center
              placeholder="请选择节目时长">
              {{
                input: () => {
                  const timers = formatterTimer(item.time);
                  return (
                    <div class={styles.programTimer}>
                      <span>{timers?.minute}</span>分
                      <span>{timers?.secord}</span>秒
                    </div>
                  );
                }
              }}
            </Field>
            <Field label="上传附件" labelAlign="top">
              {{
                input: () => (
                  <div class={styles.uploadGroup}>
                    <MUploader
                      uploadIcon={iconUploadImg}
                      maxCount={5}
                      native
                      v-model:modelValue={item.attachmentImgUrl}
                      style={{ marginTop: '6px' }}>
                      <MUploaderInside
                        uploadIcon={iconUploadVideo}
                        uploadType="VIDEO"
                        native
                        uploadSize={50}
                        accept=".mp4"
                        maxCount={3}
                        v-model:modelValue={item.attachmentVideoUrl}
                      />
                    </MUploader>
                  </div>
                )
              }}
            </Field>
          </CellGroup>
        ))}
        <div class={styles.addButtonGroup}>
          <Button
            icon="plus"
            block
            type="primary"
            plain
            class={styles.addButton}
            onClick={onAddItem}>
            添加节目
          </Button>
        </div>

        <MSticky position="bottom">
          <div class={['btnGroupFixed', styles.bottonGroup]}>
            <Button type="primary" round block onClick={onSubmit}>
              确认
            </Button>
          </div>
        </MSticky>

        {/* 时间 */}
        <Popup v-model:show={forms.timerStatus} round position="bottom">
          <DatePicker
            v-model={forms.currentDate}
            // minDate={new Date()}
            formatter={formatterDatePicker}
            onCancel={() => (forms.timerStatus = false)}
            onConfirm={({ selectedValues }) => {
              // console.log(val, 12);
              forms.startTime = selectedValues.join('-');
              forms.timerStatus = false;
            }}
          />
        </Popup>

        {/* 乐团 */}
        <Popup v-model:show={forms.orchestraStatus} round position="bottom">
          <Picker
            columns={forms.orchestraColumns}
            onCancel={() => (forms.orchestraStatus = false)}
            onConfirm={({ selectedOptions }) => {
              if (
                forms.selectOrchestra.musicGroupId != selectedOptions[0].value
              ) {
                forms.selectOrchestra.subjectAllList = [];
                forms.selectOrchestra.performerList = [];
                forms.selectOrchestra.subjectIdList = [];

                forms.selectOrchestra.musicGroupName = selectedOptions[0].text;
                forms.selectOrchestra.musicGroupId = selectedOptions[0].value;
                forms.orchestraStatus = false;
                getUserList();
              } else {
                forms.orchestraStatus = false;
              }
            }}
          />
        </Popup>

        {/* 节目时长 */}
        <Popup
          v-model:show={forms.programTimerStatus}
          round
          style={{ width: '82%' }}>
          <InputTimer
            show={forms.programTimerStatus}
            time={forms.selectOrchestra.time}
            onClose={() => (forms.programTimerStatus = false)}
            onConfirm={(val: any) => {
              const secords =
                Number(val.minute || 0) * 60 + Number(val.second || 0);
              forms.selectOrchestra.time = secords;
              forms.programTimerStatus = false;
            }}
          />
        </Popup>

        {/* 删除节目提示 */}
        <Popup v-model:show={forms.deleteStatus} round style={{ width: '82%' }}>
          <div class={styles.popupContainer}>
            <h2 class={styles.popupTitle}>删除节目</h2>
            <div class={styles.popupContent}>
              <p class={styles.tipContent}>
                删除<span>《节目{toChinesNum(forms.deleteIndex + 1)}》</span>
                ，删除后内容不可恢复
              </p>
            </div>
            <div class={['btnGroupPopup']}>
              <Button
                type="primary"
                round
                onClick={() => {
                  forms.detail.splice(forms.deleteIndex, 1);
                  forms.deleteStatus = false;
                }}>
                确定
              </Button>
              <Button round onClick={() => (forms.deleteStatus = false)}>
                取消
              </Button>
            </div>
          </div>
        </Popup>

        {/* 表演团队 */}
        <Popup
          v-model:show={forms.teamStatus}
          round
          position="bottom"
          closeable>
          <PerformanceTeam
            show={forms.teamStatus}
            performances={forms.selectOrchestra.subjectAllList}
            selectIds={forms.selectOrchestra.subjectIdList}
            onClose={() => (forms.teamStatus = false)}
            onConfirm={(ids: any[]) => {
              forms.selectOrchestra.subjectIdList = ids;
              formatterPerformer(ids);
              forms.teamStatus = false;
            }}
          />
        </Popup>

        {/* 演员名单 */}
        <MPopup v-model:modelValue={forms.castStatus}>
          <CastModal
            subjectAllList={forms.selectOrchestra.subjectAllList}
            v-model:performerList={forms.selectOrchestra.performerList}
            onClose={() => (forms.castStatus = false)}
            onConfirm={(val: any) => {
              const subjects = val || [];
              // 选中的声部编号
              const ids: any = [];
              subjects.forEach((subject: any) => {
                ids.push(subject.subjectId);
              });
              forms.selectOrchestra.subjectIdList = ids || [];
            }}
          />
        </MPopup>
      </div>
    );
  }
});
