import React from 'react';
import { Drawer, Table } from 'kts-components-antd-x3';
import Invoice from '../../..';
import { updateUnitPriceExcludingTax, updateUnitPriceTax, dutyFree, format15 } from '../GoodsList/hook/useColumns/autoFillFn';
import { countAmountIncludeTax } from '../../../tools/calculate'
import { IGood } from '../../../InvoiceController';
import evaluate from '../../../tools/evaluate';

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

  const visible = controller.useMemo(s => s.goodsListState.importGoods.isVisibleDrawer, []);

  const topExpand = controller.useMemo(s => s.goodsListState.importGoods.topExpand, []);

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

  return (
    <Drawer
      title="商品列表"
      placement="right"
      // closable={false}
      destroyOnClose={true}
      width={983}
      onClose={onClose}
      visible={visible}
    >
      {
        topExpand &&
        <div style={{ marginBottom: 10 }}  >
          {topExpand}
        </div>
      }
      <DrawerBody />
    </Drawer>
  );
};

const DrawerBody = () => {
  const controller = Invoice.useInvoiceController();

  const columns = controller.useMemo(s => s.goodsListState.importGoods.columns, []);

  const dataSource = controller.useMemo(s => s.goodsListState.importGoods.dataSource, []);

  const pagination = controller.useMemo(s => s.goodsListState.importGoods.pagination, []);

  // const [editGood] = React.useState(controller.state.goodsListState.editGood);

  React.useEffect(() => { controller.getGoodsList && controller.getGoodsList({ pagination: { current: 1 } }) }, [controller]);

  return (
    <Table
      bordered
      size="small"
      columns={columns}
      dataSource={dataSource}
      pagination={pagination}
      onChange={pagination => { controller.getGoodsList && controller.getGoodsList({ pagination }) }}
      onRow={record => {
        return {
          onClick: () => {
            controller.run(async s => {
              Object.keys(record).filter(e => !record[e] && record[e] !== 0).forEach(e => { delete record[e] });

              // 导入时校验函数
              if (await s.goodsListState.importGoods.verifyFn(record) === false) return;

              // 没用 被编辑的货物 和 form 就退出
              if (!s.goodsListState.editGood || !s.goodsListState.form) return;

              // 导入时清空之前输入的值，使用导入的单价和税率(参考税局系统)
              record.quantity = undefined;
              record.lineAmountExcludeTax = undefined;
              record.lineAmountIncludeTax = undefined;

              // 中间数据
              const between = { ...record };
              between.itemName = getItemName(record, s.goodsListState.editGood);
              between.itemCode = getItemCode(record, s.goodsListState.editGood);
              between.itemNameOther = getItemNameOther(record, s.goodsListState.editGood);

              // 设置编辑货物
              const editGood: IGood = s.goodsListState.editGood = {
                ...s.goodsListState.editGood,
                itemModelName: undefined,
                itemModelNameSelf: undefined,
                ...between
              };

              if (editGood.taxRate) {
                editGood.taxRate = dutyFree(controller, editGood.taxRate, s.goodsListState.form, editGood)
              }

              if (`${editGood.priceIncludeTax}` === '0') {
                editGood.priceIncludeTax = undefined;
                editGood.priceExcludeTax = undefined;
              } else {
                editGood.priceExcludeTax = getPriceExcludeTax(editGood, record, s.calculatingDigits) as number;
              }

              if (editGood.quantity && editGood.priceIncludeTax) {
                editGood.lineAmountIncludeTax = countAmountIncludeTax(editGood.quantity, editGood.priceIncludeTax, s.calculatingDigits);
              }

              // 导入FORM里
              s.goodsListState.form.setFieldsValue({
                ...editGood,
              });
              // if (s.goodsListState.isMyShow) {
              //   s.goodsListState.form.setFieldsValue({
              //     ...editGood,
              //     itemName: editGood.itemNameSelf,
              //     itemModelName: editGood.itemModelNameSelf,
              //   });
              // } else {
              //   s.goodsListState.form.setFieldsValue({
              //     ...editGood,
              //   });
              // }

              s.goodsListState.importGoods.isVisibleDrawer = false;
              s.goodsListState.isTaxIncluded
                ? await updateUnitPriceExcludingTax(controller, s.goodsListState.form, record)
                : await updateUnitPriceTax(controller, s.goodsListState.form, record)
            })
          }
        };
      }}
    />
  );
};

/** 项目名称 */
// const getItemName = (record: any) => {
//   return record.shorthand
//     ? `*${record.shorthand}*${record.itemName}`
//     : record.itemName;
// };

/** 货物单价，不含税 */
const getPriceExcludeTax = (s: IGood, record: any, calculatingDigits?: number) => {
  if ((!s.taxRate && s.taxRate !== 0) || (!record.priceIncludeTax && record.priceIncludeTax !== 0)) return;

  // 单价(含税)/(1+税率) = 单价(不含税)
  return format15(evaluate(`${record.priceIncludeTax} / (1+${s.taxRate}/100)`), calculatingDigits);
};

// 获取我方名称
const getItemName = (record: any, editGood: IGood) => {

  // let shorthand;

  // shorthand = record.shorthand;
  // if (shorthand) {
  //   return `*${shorthand}*${record.itemName}`;
  // }

  // shorthand = getSN(editGood.itemName)?.shorthand;
  // if (shorthand) {
  //   return `*${shorthand}*${record.itemNameSelf}`;
  // }

  return record.itemName;
}

// 获取他方名称
const getItemNameOther = (record: any, editGood: IGood) => {
  // if (!editGood.itemName) return editGood.itemName;

  // let shorthand;

  // shorthand = record.shorthand;
  // if (shorthand) {
  //   return `*${shorthand}*${record.itemNameSelf}`;
  // }
  return record.itemName;
}

// 获取商品编号
const getItemCode = (record: any, editGood: IGood) => {

  // let shorthand;

  // shorthand = record.shorthand;
  // if (shorthand) {
  //   return `*${shorthand}*${record.itemName}`;
  // }

  // shorthand = getSN(editGood.itemName)?.shorthand;
  // if (shorthand) {
  //   return `*${shorthand}*${record.itemNameSelf}`;
  // }

  return record.productCode;
}
