<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :minHeight="340"
    :width="580"
    :title="modalTitle"
    @visible-change="handleVisibleChange"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field] || '' }}
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, nextTick, ref, computed, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { checkUserAddAble } from '/@/api/corporation/modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useUserStore } from '/@/store/modules/user';
  import { staffListApi } from '/@/api/staff/list';
  import { ListApi } from '/@/api/scene/live';
  import { bindUserList, createOrUpdate } from '/@/api/scene/list';
  import dayjs from 'dayjs';
  import { cloneDeep } from 'lodash-es';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['register', 'submit', 'tablelist'],
    setup(props, { emit }) {
      const { createMessage } = useMessage();
      const modalTitle = ref('编辑');
      const userStore = useUserStore();
      const userinfo = computed(() => userStore.getUserInfo);
      const { companyId } = userinfo.value;
      console.log('userinfovalue', userinfo.value);
      const { getCheckRole } = userStore;
      const isPropsData = reactive({
        isUpdate: true,
        isSetData: true,
        record: {},
      });
      const userIdList = reactive({
        list: [],
      });
      const schemas: FormSchema[] = [
        {
          field: 'name',
          label: '房间名称',
          component: 'Input',
          colProps: {
            span: 22,
          },
          required: true,
          componentProps: {
            maxLength: 15,
            autoComplete: 'off',
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                if (!value) {
                  return Promise.reject('请输入房间名称');
                }
                let iconRule2 =
                  /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;
                if (iconRule2.test(value)) {
                  return Promise.reject('不支持特殊符号');
                } else {
                  return Promise.resolve();
                }
              },
              trigger: 'change',
            },
          ],
        },
        {
          field: 'brandId',
          label: '房间场景',
          component: 'ApiSelect',
          itemProps: {
            validateTrigger: 'blur',
          },
          colProps: {
            span: 22,
          },
          required: true,
          componentProps: {
            api: ListApi,
            showSearch: true,
            resultField: 'list',
            labelField: 'name',
            valueField: 'id',
            immediate: true,
            params: {
              page: 1,
              limit: 1000,
            },
            onChange: brandIdChange,
          },
        },
        {
          field: 'anchorUserId',
          label: '主持人',
          component: 'ApiSelect',
          itemProps: {
            validateTrigger: 'blur',
          },
          colProps: {
            span: 22,
          },
          required: true,
          componentProps: {
            api: bindUserList,
            showSearch: true,
            disabled: true,
            resultField: 'list',
            labelField: 'userAndNick',
            valueField: 'id',
            immediate: false,
            params: {
              page: 1,
              limit: 1000,
            },
          },
        },
        {
          field: 'launchPeriod', //'effectiveStartTime',
          component: 'RangePicker',
          label: '开播时间段',
          colProps: {
            span: 22,
          },
          required: true,
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                if (!value) {
                  return Promise.reject('请选择开播时间段');
                }
                if (modalTitle.value == '查看') {
                  return Promise.resolve();
                }
                let start, end;
                if (dayjs(value[0]).isAfter(dayjs(value[1]))) {
                  start = dayjs(value[1]);
                  end = dayjs(value[0]);
                } else {
                  end = dayjs(value[1]);
                  start = dayjs(value[0]);
                }
                console.log('start', start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'), value);
                if (end.isSame(start, 'minute')) {
                  return Promise.reject('结束时间应大于开始时间');
                } else if (dayjs().isAfter(dayjs(end))) {
                  return Promise.reject('结束时间应大于当前时间');
                } else {
                  return Promise.resolve();
                }
              },
              trigger: 'change',
            },
          ],
          componentProps: {
            onChange: async (data) => {
              console.log('data', data);
              setFieldsValue({
                incrementEndTime: '',
              });
            },
            // valueFormat: 'YYYY-MM-DD HH:mm',
            format: 'YYYY-MM-DD HH:mm',
            showTime: true,
            // disabledDate: validateStartTime,
          },
        },
        // {
        //   field: 'effectiveEndTime',
        //   component: 'DatePicker',
        //   label: '计划结束时间',
        //   colProps: {
        //     span: 22,
        //   },
        //   required: true,
        //   componentProps: {
        //     // valueFormat: 'YYYY-MM-DD HH:mm',
        //     format: 'YYYY-MM-DD HH:mm',
        //     showTime: true,
        //     disabledDate: validateDate,
        //     disabledTime: validateTime,
        //   },
        // },
        {
          field: 'assistantUserId',
          component: 'ApiSelect',
          label: '助理',
          itemProps: {
            validateTrigger: 'blur',
          },
          colProps: {
            span: 22,
          },
          required: false,
          componentProps: {
            api: staffListApi,
            showSearch: true,
            resultField: 'list',
            labelField: 'nickName',
            valueField: 'id',
            immediate: true,
            params: {
              page: 1,
              limit: 1000,
              companyId: companyId,
            },
            onChange: async (data) => {
              console.log('data', data, arguments);
            },
          },
        },
        {
          field: 'id',
          component: 'Input',
          label: '测试',
          ifShow: false,
          // slot: 'text',
        },
      ];
      const [
        registerForm,
        {
          getFieldsValue,
          // validateFields,
          setFieldsValue,
          // setProps
          updateSchema,
          resetFields,
          validate,
        },
      ] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner(async (data) => {
        data && onDataReceive(data);
      });
      function onDataReceive(data) {
        isPropsData.isUpdate = data.isUpdate || false;
        isPropsData.isSetData = data.isSetData || false;
        modalTitle.value = data.isSetData ? '查看' : data.isUpdate ? '编辑' : '新增';
        // const  = ref('编辑');
        isPropsData.record = data.record || {};
        if (data.isUpdate) {
          //编辑
          setFieldsValue({
            ...data.record,
          });
          updateSchema(
            schemas.map((ele, index) => {
              return {
                ...ele,
                componentProps: {
                  ...ele.componentProps,
                  disabled: index < 3 && index != 0 ? true : false,
                },
                slot: '',
              };
            }),
          );
          if (data.record && data.record.brandId) {
            brandIdChange(data.record.brandId);
          }
          if (data.record && data.record.anchorUserId) {
            UserIdChange(data.record.anchorUserId);
          }
        } else if (data.isSetData) {
          //查看
          let setSchemas = [];
          console.log('setFieldsValue', data.record);
          schemas.map((ele) => {
            let setSchemasItem = {
              ...ele,
              componentProps: {
                ...ele.componentProps,
                disabled: true,
              },
              // slot: 'text',
            };
            setSchemas.push(cloneDeep(setSchemasItem));
          });
          updateSchema(setSchemas);
          setFieldsValue(data.record);
        } else {
          //新增
          resetFields();
          updateSchema(
            schemas.map((ele) => {
              return {
                ...ele,
                componentProps: {
                  ...ele.componentProps,
                  disabled: false,
                },
                // slot: '',
              };
            }),
          );
        }
      }
      const handleSubmit = async () => {
        const values = await validate();
        const { launchPeriod } = values;
        console.log('validate', values, launchPeriod);
        let apiData = {
          ...values,
          effectiveEndTime:
            new Date(launchPeriod[0]).getTime() > new Date(launchPeriod[1]).getTime()
              ? new Date(launchPeriod[0]).getTime()
              : new Date(launchPeriod[1]).getTime(),
          effectiveStartTime:
            new Date(launchPeriod[0]).getTime() > new Date(launchPeriod[1]).getTime()
              ? new Date(launchPeriod[1]).getTime()
              : new Date(launchPeriod[0]).getTime(),
        };
        if (!isPropsData.isSetData) {
          apiData.id = isPropsData.record.id;
          await createOrUpdate(apiData);
          createMessage.success(t('common.optSuccess'));
        }
        resetFields();
        closeModal();
        emit('success');
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      function handleClose() {
        resetFields();
      }
      function brandIdChange(brandId) {
        let disabled = isPropsData.isUpdate ? isPropsData.isUpdate : brandId ? false : true;
        if (!brandId) {
          return;
        }
        console.log('userinfo.value.id,', userinfo.value.id, getCheckRole(['staff']));
        if (getCheckRole(['staff'])) {
          disabled = true;
          setFieldsValue({
            anchorUserId: userinfo.value.id,
          });
        } else if (!disabled) {
          setFieldsValue({
            anchorUserId: '',
          });
        }
        updateSchema({
          field: 'anchorUserId',
          componentProps: {
            immediate: true,
            disabled,
            params: {
              page: 1,
              limit: 1000,
              id: brandId,
            },
            onChange: UserIdChange,
          },
        });
      }
      function UserIdChange(data) {
        console.log('UserIdChange,', data, userinfo.value.id, isPropsData.isUpdate);
        if (!isPropsData.isUpdate) {
          setFieldsValue({
            assistantUserId: '',
          });
        }
        updateSchema({
          field: 'assistantUserId',
          componentProps: {
            api: async function (params) {
              const res = await staffListApi({ ...params, id: data });
              return res.list.filter((ele) => {
                return ele.id !== data;
              });
            },
            showSearch: true,
            resultField: 'list',
            labelField: 'nickName',
            valueField: 'id',
            immediate: true,
            params: {
              page: 1,
              limit: 1000,
            },
            onChange: async (data) => {
              console.log('data', data, arguments);
            },
          },
        });
      }
      return {
        t,
        modalTitle,
        register,
        userIdList,
        schemas,
        isPropsData,
        registerForm,
        brandIdChange,
        UserIdChange,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        closeModal,
        handleClose,
        getFieldsValue,
        setFieldsValue,
        // nextTick,
      };
    },
  });
</script>
<style lang="less">
  .ant-form-item-control-input {
    div {
      div {
        width: 100%;
      }
    }
  }
</style>
