/* 编号规则
 * @Author: Li Hanlin
 * @Date: 2022-11-09 14:44:44
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-12-14 18:27:22
 */

import * as React from 'react';
import { useState, useMemo, useRef } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import { doFetch } from '@/utils/doFetch';
import { message } from 'antd';
import AddRules from './AddRules';
import _ from 'lodash';

function Rules(props) {
  const actionRef = useRef(),
    formRef = useRef();
  const [drawer, setDrawer] = useState({
    visible: false,
  });

  const urlParams = {
    save: '/base/bmNumberRule/save',
    remove: '/base/bmNumberRule/deleteByNoTypeId',
    list: '/base/bmNumberRule/queryList',
    detail: '/base/bmNumberRule/queryByNoTypeId',
  };

  const detail = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              item: row,
              title: '详情',
              val: 'detail',
              title: row.userName + '的详细信息',
            }));
          },
        }}
      >
        详情
      </PremButton>
    );
  };

  const edit = (text, row, i, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              detailpath: urlParams.detail,
              params: { noTypeId: row?.id },
              title: '编辑',
              val: 'edit',
              onFinish: async (vals) => {
                vals.nrList.other = _.pick(vals.nrList.other, [
                  'formatType',
                  'increaseList',
                  'noRuleCode',
                  'sort',
                ]);
                vals.nrList.value = vals.nrList.value.map((it) => {
                  return _.pick(it, ['id', 'noContent', 'noRuleCode', 'sort', 'paramList']);
                });
                console.log('1214', vals);
                let params = { ...vals };
                params.nrList = [];
                params.nrList = params.nrList.concat(vals?.nrList.value);
                if (vals?.nrList.other.sort) {
                  vals.nrList.other.increaseList = Array.from(
                    Array(vals?.nrList.value.length + 1),
                    (_, index) => index + 1,
                  ).filter((it) => it !== vals?.nrList.other.sort + 1);
                  params.nrList.splice(vals?.nrList.other.sort, 0, vals?.nrList.other);
                  params.nrList.forEach?.((it, i) => {
                    it.sort = i + 1;
                  });
                } else {
                  message.warning('请选择顺序递增规则的位置！');
                  return;
                }
                params.id = row?.id;
                console.log('11111', params);
                let res = await doFetch({
                  url: urlParams.save,
                  params,
                });
                if (res.code === '0000') {
                  message.success('编辑成功！');
                  setDrawer((s) => ({
                    ...s,
                    visible: false,
                  }));
                  actionRef.current.reload();
                }
              },
            }));
          },
        }}
      >
        编辑
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否删除该规则?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            let res = await doFetch({ url: urlParams.remove, params: { noTypeId: row.id } });
            if (res.code === '0000') {
              message.success('删除成功！');
              setDrawer((s) => ({
                ...s,
                visible: false,
              }));
              actionRef.current.reload();
            }
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setDrawer);
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, row, _, action) => [edit(text, row, _, action), remove(text, row, _, action)],
    });
  }, []);

  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">编号规则</h3>}
        columns={columns}
        pagination={false}
        path={urlParams.list}
        actionRef={actionRef}
        pageextra={'add'}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            type: 'primary',
            disabled: false,
            onClick: () => {
              setDrawer((s) => ({
                ...s,
                visible: true,
                item: null,
                detailpath: null,
                title: '新增',
                val: 'add',
                onFinish: async (vals) => {
                  console.log('myvals:', vals);
                  let params = { ...vals };
                  //console.log('vals:', vals);
                  // for (let i in vals) {
                  //   if (i == 'nrList') {
                  //     let reshow = {
                  //       value: vals[i].filter((it) => it.noRuleCode != 'increasing_order'),
                  //       other: vals[i].filter((it) => it.noRuleCode == 'increasing_order')[0] || {},
                  //     };
                  //     reshow.other.increaseList = reshow.other.increaseList.maps((it) => {
                  //       return reshow.value.filter((item) => item.sort == it)[0].id;
                  //     });
                  //     reshow.other.sort =
                  //       reshow.other.sort == 1 ? reshow.other.sort : reshow.other.sort - 1;
                  //     //console.log('reshow', reshow);
                  //   }
                  // }
                  params.nrList = [];
                  params.nrList = params.nrList.concat(vals?.nrList.value);
                  if (vals?.nrList.other.sort) {
                    vals.nrList.other.increaseList = Array.from(
                      Array(vals?.nrList.value.length + 1),
                      (_, index) => index + 1,
                    ).filter((it) => it !== vals?.nrList.other.sort + 1);
                    params.nrList.splice(vals?.nrList.other.sort, 0, vals?.nrList.other);
                    params.nrList.forEach?.((it, i) => {
                      it.sort = i + 1;
                    });
                  } else {
                    message.warning('请选择顺序递增规则的位置！');
                    return;
                  }
                  let res = await doFetch({
                    url: urlParams.save,
                    params,
                  });
                  if (res.code === '0000') {
                    message.success('新增成功！');
                    setDrawer((s) => ({
                      ...s,
                      visible: false,
                    }));
                    actionRef.current.reload();
                  }
                },
              }));
            },
          },
        }}
      />

      <DrawerPro
        fields={columns}
        // detailpath={urlParams.detail}
        // params={{ id: drawer?.item?.id }}
        defaultFormValue={drawer?.item ?? {}}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setDrawer((s) => ({
            ...s,
            visible: false,
          }));
        }}
        {...drawer}
      />
    </div>
  );
}

export default Rules;
