import React from 'react';
import Invoice from '../../..';
import { Button, Drawer, Select, Modal, Input as InputAntd, Form, Tree, message } from 'kts-components-antd-x3';
import { chain, bignumber } from 'mathjs';
import { Input, NumberPicker } from '@formily/antd-components';
import { format15 } from '../GoodsList/hook/useColumns/autoFillFn';
import { LineAttributeType } from '../../../InvoiceController';
import IGood from '../../../InvoiceController/InvoiceControllerState/GoodsListState/IGood';
import { countTaxAmount, countAmountExcludeTax, countPrice } from '../../../tools/calculate';
import { bytesLnegth, cutStr } from '../../../tools/strringFn';
import {
  SchemaForm,
  FormButtonGroup,
  createAsyncFormActions,
  SchemaMarkupField as Field,
  FormEffectHooks,
} from '@formily/antd';
import './index.less';
import { TaxClassificationModal } from "../../../..";

const { TreeNode } = Tree;
const { confirm } = Modal;

export default () => {
  const controller = Invoice.useInvoiceController();

  const visible = controller.useMemo(s => s.goodsListState.endowCode.endowcodeGoodIndex.length > 0, []);

  const [defaultValue, setDefaultValue] = React.useState<IGood>();

  const onClose = React.useCallback(() => {
    controller.pipeline(async (s) => {
      s.goodsListState.endowCode.endowcodeGoodIndex = [];
    })();
  }, [controller]);

  // 计算赋码默认值
  React.useEffect(() => {
    if (visible) {
      controller.pipeline(async s => {
        const endowcodeGoodIndex = s.goodsListState.endowCode.endowcodeGoodIndex.filter(i => {
          const good = s.goodsListState.goodsMap.get(i);
          if (!good) return false;

          return good.lineAttribute !== LineAttributeType.折扣行;
        })

        const good = s.goodsListState.goodsMap.get(s.goodsListState.endowCode.endowcodeGoodIndex[0]);
        if (!good) return;

        const getDefaultValue = s.goodsListState.endowCode.getDefaultValue;
        if (getDefaultValue) {
          setDefaultValue(await getDefaultValue({ ...good }, endowcodeGoodIndex.length));
        } else {
          if (endowcodeGoodIndex.length === 1) {
            setDefaultValue(good);
          } else {
            setDefaultValue({ taxRate: good.taxRate } as any);
          }
        }
      })()
    } else {
      setDefaultValue(undefined);
    }
  }, [visible])

  return (
    <Drawer
      title="赋码"
      placement="right"
      destroyOnClose={true}
      closable={false}
      width={383}
      onClose={onClose}
      visible={visible}
    >
      {defaultValue && <DrawerBody defaultValue={defaultValue} />}
    </Drawer>
  );
};

const DrawerBody = (props: { defaultValue: IGood }) => {

  const controller = Invoice.useInvoiceController();

  const { defaultValue } = props;

  const actions = React.useMemo(() => createAsyncFormActions(), []);

  const taxClassificationProps = controller.useMemo(s => s.taxClassificationProps, []);

  /** 免税类型 是否需要 */
  const isTaxFreeTypeNeeded = controller.useMemo(s => s.goodsListState.endowCode.isTaxFreeTypeNeeded, []);

  /** 税率 是否禁用 */
  const readOnlyTaxRate = controller.useMemo(s => {
    if (s.goodsListState.endowCode.getReadOnlyTaxRate) {
      return s.goodsListState.endowCode.getReadOnlyTaxRate(s.goodsListState);
    } else {
      return false;
    }
  }, [])

  /** 优惠政策 是否禁用 */
  const readOnlyFavouredPolicy = controller.useMemo(s => {
    if (s.goodsListState.endowCode.getReadOnlyFavouredPolicy) {
      return s.goodsListState.endowCode.getReadOnlyFavouredPolicy(s.goodsListState);
    } else {
      return false;
    }
  }, [])

  /** 税率列表 */
  const taxRateList = controller.useMemo(s => s.goodsListState.taxRateList.map((e) => ({ label: `${e}%`, value: e })), []);

  /** 免税类型 列表 */
  const taxFreeTypeList = controller.useMemo(s => s.goodsListState.endowCode.taxFreeTypeList, []);

  /** 优惠政策类型列表 */
  const favouredPolicyNameList = controller.useMemo(s => s.goodsListState.endowCode.favouredPolicyNameList, []);

  /** 优惠政策类型列表 */
  // const getTaxCategoryCodeTree = controller.useMemo(s => s.goodsListState.endowCode.getTaxCategoryCodeTree, []);

  /** 税率 */
  const [taxRate, setTaxRate] = React.useState<number>(0);

  /** 税收分类编码 选择组件 */
  const ShowSearch = React.useCallback(props => {

    const [dataSource, setDataSource] = React.useState<any[]>([]);

    const onSearch = React.useCallback(async e => {
      const arr = await controller.state.goodsListState.endowCode.getTaxCategoryCodeList(e);
      setDataSource(arr);
    }, [])

    const onChange = React.useCallback((value: string) => {
      if (props.onChange) {
        props.onChange(value);
      }

      const info = dataSource.filter(i => i.value === value)[0];
      if (!info) return;

      // !readOnlyTaxRate && actions.setFieldState('taxRate', async s => {
      //   if (info.taxRate || info.taxRate === 0) {
      //     s.value = info.taxRate
      //   }
      // });

      actions.setFieldState('shorthand', async (s) => {
        if (info.shorthand) {
          s.value = info.shorthand
        }
      });
    }, [actions, dataSource, readOnlyTaxRate])

    return (
      <Select
        {...props}
        showSearch
        showArrow={false}
        notFoundContent={null}
        filterOption={false}
        onSearch={onSearch}
        onChange={onChange}
      >
        {dataSource.map(e => <Select.Option key={e.value} value={e.value}>{e.label}</Select.Option>)}
      </Select>
    )
  }, [controller, actions])

  /** 税收分类编码 选择组件2 */
  const ShowSearch2 = React.useCallback(props => {

    // 是否显示
    const [visible, setVisible] = React.useState(false);

    // 税收分类编码树
    const [list, setList] = React.useState<any[]>();

    // 搜索条件
    const [filter, setFilter] = React.useState<{
      /** 税收分类编码 */
      taxCategoryCode?: string,

      /** 货物和劳务名称/简称 */
      val?: string
    }>();

    /** 创建 树节点 */
    const createTreeNode = React.useCallback(() => {
      if (!list) return <></>;

      return ctn(list);

      function title(label: string) {
        if (!filter) return label;
        label = (filter.taxCategoryCode ? label.split(new RegExp(filter.taxCategoryCode, 'g')) : [label]).join(`<span style="color: #1890ff;">${filter.taxCategoryCode}</span>`);
        label = (filter.val ? label.split(new RegExp(filter.val, 'g')) : [label]).join(`<span style="color: #1890ff;">${filter.val}</span>`);
        return <span dangerouslySetInnerHTML={{ __html: label }} />
      }

      function ctn(l: any[], p = '0') {
        if (!l || !l.length) return [<></>];
        return l.filter(e => e.pid === p).map(e => {
          return (
            <TreeNode title={title(e.label)} key={e.id}>
              {ctn(l, e.id)}
            </TreeNode>
          )
        })
      }
    }, [list, filter])

    /** 点击了节点 */
    const onSelect = React.useCallback((e: string[]) => {
      const id = e[0];

      // 是否叶子节点
      if (list?.filter(e => e.pid === id).length !== 0) { return; }

      const info = list?.filter(e => e.id === id)[0];

      // !readOnlyTaxRate && actions.setFieldState('taxRate', async s => {
      //   if (info.taxRate || info.taxRate === 0) {
      //     s.value = info.taxRate
      //   }
      // });

      actions.setFieldState('taxClassificationCode', async s => {
        if (info.id) {
          s.value = info.id
        }
      });

      actions.setFieldState('shorthand', async (s) => {
        if (info.shorthand) {
          s.value = info.shorthand
        }
      });

      setVisible(false);
    }, [list, actions, readOnlyTaxRate])

    React.useEffect(() => {
      (async () => {
        const fn = controller.state.goodsListState.endowCode.getTaxCategoryCodeTree || (async () => []);
        const list = await fn(filter?.taxCategoryCode, filter?.val);
        setList(list || []);
      })()
    }, [filter])

    React.useEffect(() => {
      if (visible) {
        setList([])
      }
    }, [visible])

    return (
      <>
        <InputAntd readOnly value={props.value} addonAfter={<Button size="small" type="link" onClick={() => { setVisible(true) }} >点击选择</Button>} />
        <Drawer
          title="税收分类编码"
          visible={visible}
          width={500}
          onClose={() => { setVisible(false) }}
        >
          <Form key={`${visible}`} >
            <Form.Item label="产品或服务简称" >
              <InputAntd onChange={e => { setFilter({ ...filter, val: e.target.value }) }} />
            </Form.Item>
            <Form.Item label="税收分类编码">
              <InputAntd onChange={e => { setFilter({ ...filter, taxCategoryCode: e.target.value }) }} />
            </Form.Item>
          </Form>
          {
            (list && list.length > 0)
              ? <Tree
                defaultExpandAll
                selectedKeys={[]}
                onSelect={onSelect}
              >
                {createTreeNode()}
              </Tree>
              : <span style={{ color: '#00000073' }} >请输入“产品或服务简称”或“税收分类编码”查找数据。</span>
          }
        </Drawer>
      </>
    )
  }, [controller, actions])

  /** 税收分类编码 选择组件3 */
  const ShowSearch3 = React.useCallback(props => {
    const [open, setOpen] = React.useState(false);

    const [list, setList] = React.useState<any>([]);

    const onSearch = React.useCallback(async (value: any = null) => {
      if(value?.target?.value){
        const arr = await controller.state.goodsListState.endowCode.onSearchTaxClassificationCode(value?.target?.value);
        const list: any[] = arr.map((item: any)=> {
          return {
            ...item,
            title: `${item.productName} ${item.taxCategoryCode}`,
            key: item.taxCategoryCode,
            isLeaf: true
          }
        });
        setList(list);
      } else {
        await onLoad();
      }
    }, []);

    const onLoad = React.useCallback(async (value?: any) => {
      const arr = await controller.state.goodsListState.endowCode.onLoadTaxClassificationCode(value?.taxCategoryCode);
      const data: any[] = arr.map((item: any)=> {
        return {
          ...item,
          title: `${item.productName} ${item.taxCategoryCode}`,
          key: item.taxCategoryCode
        }
      });

      const treeData = optimizeTreeData(data);

      if(value?.key) {
        setList((origin: any)=> {
          updateTreeData(origin, value.key, treeData)
        });
      } else {
        setList(treeData);
      }
      return [];
    }, []);

    const onClick = React.useCallback(async () => {
      setOpen(true);
      await onLoad();
    }, []);

    const onSelect = React.useCallback((key: any, info: any) => {
      // !readOnlyTaxRate && actions.setFieldState('taxRate', async s => {
      //   if (info.node.taxRate || info.taxRate === 0) {
      //     s.value = info.node.taxRate
      //   }
      // });

      actions.setFieldState('taxClassificationCode', async s => {
        if(info.node.taxCategoryCode) {
          s.value = info.node.taxCategoryCode
        }
      });

      actions.setFieldState('shorthand', async (s) => {
        if (info.node.shorthand){
          s.value = info.node.shorthand
        }
      });

      setOpen(false);
    }, [controller, actions]);

    const optimizeTreeData = (data: any): any => {
      return data.map((item: any)=> {
        return {
          ...item,
          selectable: item?.hzx === 'N',
          isLeaf: item?.hzx === 'N'
        }
      });
    }

    const updateTreeData = (list: any, key: React.Key, children: any): any => {
      const data = list.map((node: any) => {
        if (node.key === key) {
          return {
            ...node,
            children
          };
        }
        if (node.children) {
          return {
            ...node,
            children: updateTreeData(node.children, key, children)
          };
        }
        return node;
      });
      setList(data);
      return data;
    }

    return (
      <>
        <InputAntd readOnly onClick={onClick} value={props.value} />
        <TaxClassificationModal
          list={list}
          open={open}
          onSelect={onSelect}
          onCancel={()=> {setOpen(false)}}
          onSearch={onSearch}
          onLoad={onLoad}
        />
      </>
    )
  }, [controller, actions])

  // 是否享受优惠政策
  const [favouredPolicyMark, setFavouredPolicyMark] = React.useState<number>(0);

  // 确定
  const onSubmit = React.useCallback(values => {
    controller.pipeline(async s => {

      const endowCodeGood = s.goodsListState.endowCode.endowcodeGoodIndex.map(e => s.goodsListState.goodsMap.get(e));

      // 赋码
      endowCodeGood.forEach(good => {
        if (!good) return;

        good.shorthand = values.shorthand;
        good.taxClassificationCode = values.taxClassificationCode;
        good.taxRate = values.taxRate;
        good.taxFreeType = values.taxFreeType;
        good.favouredPolicyMark = values.favouredPolicyMark;
        good.favouredPolicyName = values.favouredPolicyName;

        // 无论是否含税，都保持价税合计不变
        good.taxAmount = countTaxAmount(good.lineAmountIncludeTax || 0, s.goodsListState.deduction, values.taxRate);
        if (good.taxAmount || good.taxAmount === 0 ) {
          good.lineAmountExcludeTax = countAmountExcludeTax(good.lineAmountIncludeTax || 0, good.taxAmount); 
        }
        if (good.lineAmountExcludeTax && good.quantity) {
          good.priceExcludeTax = countPrice(good.lineAmountExcludeTax, good.quantity, controller.state.calculatingDigits) as any;
        }

      });

      s.goodsListState.goodsList = s.goodsListState.goodsList.slice();
      s.goodsListState.endowCode.endowcodeGoodIndex = [];
    })();
  }, [controller]);

  const effects = React.useCallback(() => {
    // 税率变化
    FormEffectHooks.onFieldValueChange$('taxRate').subscribe((e) => {
      setTaxRate(e.value);
      actions.setFieldState('taxFreeType', async (s) => {
        if (e.value !== 0)
          s.value = undefined;
      });
    });

    // 是否享受优惠政策
    FormEffectHooks.onFieldValueChange$('favouredPolicyMark').subscribe((e) => {
      setFavouredPolicyMark(e.value);
      actions.setFieldState('favouredPolicyName', async (s) => {
        if (e.value === 0)
          s.value = undefined;
      });
    });
  }, [actions]);

  // 更新 税收分类编码列表
  React.useEffect(() => {
    if (controller.getTaxCategoryCodeList) controller.getTaxCategoryCodeList();
  }, [controller]);

  return (
    <SchemaForm actions={actions} previewPlaceholder=" "  components={{ ...components, showSearch: !!controller.state.goodsListState.endowCode.onLoadTaxClassificationCode ? ShowSearch3 : ShowSearch }} effects={effects}>
      <FormButtonGroup>
        <Field
          name="taxClassificationCode"
          type="showSearch"
          title="税收分类编码"
          // enum={taxCategoryCodeList}
          default={defaultValue?.taxClassificationCode}
          x-rules={[{ message: '请选择税收分类编码', required: true }]}
        />
        <Field
          name="shorthand"
          type="string"
          readOnly
          default={defaultValue?.shorthand}
          title="商品和服务分类简称"
        />
        <Field
          name="taxRate"
          type="string"
          title="税率"
          x-component-props={{ disabled: readOnlyTaxRate }}
          default={defaultValue?.taxRate ?? 0}
          enum={taxRateList}
          x-rules={[{ message: '请选择税率', required: true }]}
        />
        {taxRate === 0 && isTaxFreeTypeNeeded &&
          <Field
            name="taxFreeType"
            type="string"
            title="免税类型"
            x-component-props={{ disabled: readOnlyTaxRate }}
            default={defaultValue?.taxFreeType}
            enum={taxFreeTypeList}
            x-rules={[{ message: '请选择免税类型', required: true }]}
          />
        }
        <Field
          name="favouredPolicyMark"
          type="number"
          title="是否享受优惠政策"
          x-component-props={{ disabled: readOnlyFavouredPolicy }}
          enum={[
            { label: '是', value: 1 },
            { label: '否', value: 0 },
          ]}
          default={defaultValue?.favouredPolicyMark ?? 0}
          x-rules={[{ message: '请选择是否享受优惠政策', required: true }]}
        />
        {favouredPolicyMark === 1 &&
          <Field
            name="favouredPolicyName"
            type="string"
            title="优惠政策类型"
            x-component-props={{ disabled: readOnlyFavouredPolicy }}
            enum={favouredPolicyNameList}
            default={defaultValue?.favouredPolicyName}
            x-rules={[{ message: '请选择是否享受优惠政策', required: true }]}
          />
        }
      </FormButtonGroup>

      <span className="kts-invoice-operate-goods-endow-code-button-list">
        <Button onClick={() => { actions.submit(onSubmit) }} type="primary">
          确定
        </Button>
        <Button onClick={() => { controller.pipeline(async s => (s.goodsListState.endowCode.endowcodeGoodIndex = []))() }}>
          取消
        </Button>
      </span>
    </SchemaForm>
  );
};

const components = {
  string: Input,
  number: NumberPicker,
};
