<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.scenes.bindAnchor')"
    width="800px"
    @ok="handleSubmit"
    @cancel="clearSelectedRowKeys"
  >
    <div class="pt-2px pr-3px">
      <BasicTable
        @register="registerTable"
        :searchInfo="searchInfo"
        :rowSelection="{ type: 'checkbox', onChange: handleSelect }"
      >
        <template #headerTop>
          <div class="pt-4 pb-4">
            {{ t('routes.scenes.sceneName') }}： {{ headerInfo?.sceneName }}
            {{ t('routes.scenes.anchorRoom') }}：{{ headerInfo?.name }}</div
          >
        </template>
        <template #canShowSwitch="{ record }">
          <div>
            <Switch
              :disabled="!SelectRowsList.includes(record.id)"
              v-model:checked="checkedObj[record.id]"
              @change="onchange(record)"
              :checkedChildren="t('layout.setting.on')"
              :unCheckedChildren="t('layout.setting.off')"
            />
          </div>
        </template>
      </BasicTable>
      <!-- <BasicForm @register="registerForm" :model="model" /> -->
    </div>
    <template #centerFooter>
      <!-- <a-button>xxxx</a-button> -->
    </template>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref, computed } from 'vue';
  import { Switch } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  // import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { BasicTable, useTable, BasicColumn, FormSchema } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { checkUserAddAble } from '/@/api/corporation/modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  // bindAnchorListApi
  import { bindOldAnchorListApi, bindUserApi } from '/@/api/scene/live';
  import { bindAnchorListParam } from '/@/api/scene/model';
  // import { Time } from '/@/components/Time';
  // import { useUserStore } from '/@/store/modules/user';

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const schemas: FormSchema[] = [
    {
      field: 'own',
      label: t('routes.scenes.own'),
      component: 'Input',
    },
  ];
  const columns: BasicColumn[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      ellipsis: true,
      fixed: 'left',
      width: 130,
    },
    {
      title: t('routes.scenes.userName'),
      dataIndex: 'nickName',
      width: 100,
    },
    {
      title: t('common.roleName'),
      dataIndex: 'roleName',
      width: 100,
    },

    {
      title: t('common.mobile'),
      dataIndex: 'phone',
      width: 100,
    },
    {
      title: t('routes.scenes.canShow'),
      dataIndex: 'canShow',
      slots: { customRender: 'canShowSwitch' },
      width: 140,
    },
    // {
    //   title: t('routes.scenes.bindTime'),
    //   dataIndex: 'createTime',
    //   width: 100,
    //   customRender: ({ record }) => {
    //     return (
    //       record.createTime &&
    //       h(Time, {
    //         value: record.createTime,
    //         mode: 'datetime',
    //       })
    //     );
    //   },
    // },
  ];
  export default defineComponent({
    components: { BasicModal, BasicTable, Switch },
    props: {
      userData: { type: Object },
    },
    emits: ['register', 'success'],
    setup(_, { emit }) {
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      const SelectRowsList = computed(() => {
        const data = getSelectRowKeys();
        return data;
      });
      const mapCheckedValue = computed(() => (key) => {
        return key === 1 ? true : false;
      });
      const checked = ref<boolean>(false);
      const checkedObj = ref({});
      const headerInfo = reactive<Recordable>({});
      const searchInfo = reactive<Recordable>({});

      const [
        registerTable,
        {
          reload,
          getSelectRows,
          getSelectRowKeys,
          clearSelectedRowKeys,
          setSelectedRowKeys,
          // getRawDataSource,
        },
      ] = useTable({
        title: t('routes.scenes.anchorList'),
        api: bindOldAnchorListApi,
        columns: columns,
        useSearchForm: false,
        // formConfig: searchForm,
        showTableSetting: false,
        maxHeight: 600,
        tableSetting: { fullScreen: true },
        showIndexColumn: false,
        // immediate: true,
        // isCanResizeParent: true,
        rowKey: 'id',
        pagination: false,
        clickToRowSelect: false,
        bordered: true,
        afterFetch: (data) => {
          let bindIds = [];
          data.map((i) => {
            i.canShow = i.canShow == 1 ? true : false;
            checkedObj.value[i.id] = i.canShow;
            if (i.isBind === 1) {
              bindIds.push(i.id);
            }
            return i;
          });
          setSelectedRowKeys(bindIds);
        },
      });

      function onDataReceive(data) {
        console.log('Data Received', data.id);
        searchInfo.brandId = data.id;
        headerInfo.name = data.name;
        headerInfo.sceneName = data.sceneName;
        searchInfo.limit = 1000;
        searchInfo.page = 1;
        reload();
        // const rawData = getRawDataSource();

        // if (rawData.list.re) {
        //   console.log('存在已邦，选择');
        //   setSelectedRowKeys([Number(data.bindShowerId)]);
        // }
      }
      const handleSubmit = async () => {
        try {
          const rows = getSelectRows();
          // const rawData = getRawDataSource();
          let paramsRow: bindAnchorListParam[];
          console.log('rawData', 'rows', rows, checkedObj.value);
          // if (rows?.length > 0) {
          //   paramsRow = rows.map((row) => {
          //     return {
          //       brandId: String(searchInfo.brandId),
          //       canShow: row.canShow ? 1 : 0,
          //       type: 1,
          //       userId: String(row.id),
          //     } as bindAnchorListParam;
          //   });
          //   await bindUserApi(paramsRow);
          //   createMessage.success(t('common.optSuccess'));
          // } else {
          paramsRow = rows.map((item) => {
            let param: bindAnchorListParam = {};
            param.canShow = checkedObj.value[item.id] ? 1 : 0;
            param.type = 1;
            param.brandId = searchInfo.brandId;
            param.userId = String(item.id);
            return param;
          });
          console.log('paramsRow', paramsRow);
          await bindUserApi({
            brandList: paramsRow,
            brandId: searchInfo.brandId,
          });
          createMessage.success(t('common.optSuccess'));
          // }
          closeModal();
          emit('success');
          clearSelectedRowKeys();
        } catch (error) {
          console.log('error', error);
        }
      };
      const handleSelect = async () => {
        // const keys = getSelectRowKeys();
        // console.log('key', key);
      };
      const handleChange = (val, row) => {
        console.log('val,row', val, row);
        // updateTableDataRecord('canShow', values);
        // updateTableDataRecord
      };
      const onchange = (val, row) => {
        console.log('val,row', val, row, checkedObj.value);
      };
      return {
        register,
        schemas,
        registerTable,
        handleSubmit,
        searchInfo,
        closeModal,
        handleSelect,
        headerInfo,
        clearSelectedRowKeys,
        handleChange,
        t,
        checked,
        SelectRowsList,
        mapCheckedValue,
        checkedObj,
        onchange,
      };
    },
  });
</script>
