import { Checkbox, message } from 'ant-design-vue';
import $ from 'jquery';
import { loadProfile } from '../hooks/commonMethods';
import { waitTime } from '../../../../../packages/utils/common';
//从服务器获取列信息
let showCols = [];
const getAndCols = async () => {
  await loadProfile(['receip-main-list'])
    .then((res) => {
      showCols = res[0].cols;
      for (let i = 0; i < showCols.length; i++) {
        showCols[i].title = showCols[i].Name;
        showCols[i].dataIndex = showCols[i].Field;
        if (showCols[i].dataIndex == 'ProductSeries') {
          showCols[i].treeOption = [
            {
              id: '1',
              name: '成品',
              children: [
                {
                  id: '2',
                  name: '成品_纯丙烯酸酯',
                },
                {
                  id: '3',
                  name: '成品_纯丙烯酸酯_0.5kg包装',
                },
                {
                  id: '4',
                  name: '成品_纯丙烯酸酯_20kg包装',
                },
                {
                  id: '5',
                  name: '成品_纯丙烯酸酯_200kg包装',
                },
                {
                  id: '6',
                  name: '成品_纯丙烯酸酯_40kg包装',
                },
                {
                  id: '7',
                  name: '成品_纯丙烯酸酯_50kg包装',
                },
              ],
            },
            {
              id: '8',
              name: '配件',
              children: [
                {
                  id: '9',
                  name: '配件_过滤袋',
                  children: [
                    {
                      id: '10',
                      name: '配件_过滤袋_27微米',
                    },
                    {
                      id: '11',
                      name: '配件_过滤袋_28微米',
                    },
                    {
                      id: '12',
                      name: '配件_过滤袋_29微米',
                    },
                    {
                      id: '13',
                      name: '配件_过滤袋_30微米',
                    },
                  ],
                },
                {
                  id: '14',
                  name: '配件_包装桶',
                  children: [
                    {
                      id: '15',
                      name: '配件_包装桶_塑胶桶',
                    },
                    {
                      id: '16',
                      name: '配件_包装桶_铁桶',
                    },
                  ],
                },
              ],
            },
          ];
        }
      }
      showCols = formatCols(showCols);
    })
    .finally(() => {});
};
// const getAndCols = async () => {
//   await loadProfile(['supplier-info'])
//     .then((res) => {
//       showCols = formatCols(res);
//     })
//     .finally(() => {});
// };

const _getComBoxlabel = (record, col) => {
  let label = '';
  if (typeof col.Option == 'undefined') {
    label = record[col.Field];
    return;
  }
  for (let i = 0; i < col.Option.length; i++) {
    if (col.Option[i].value == record[col.Field]) {
      label = col.Option[i].label;
      break;
    }
  }
  return label;
};
const _getCheckBox = (record, col) => {
  return <Checkbox checked={record[col.Field]} disabled={true}></Checkbox>;
};

const formatCols = function (data) {
  if (data.length == 0) {
    return;
  }
  const tempArray = [];
  if (data.length > 0) {
    const cols = data.filter((item) => {
      return item.Visible == true;
    });

    for (let i = 0; i < cols.length; i++) {
      if (cols[i].Style.toLowerCase() == 'textbox') {
        const tempItem = {
          title: cols[i].Name,
          dataIndex: cols[i].Field,
          width: cols[i].width,
          resizable: true,
          align: 'center',
          hideInSearch: cols[i].ifshowInQueryForm ? false : true, //是否生成到最终的查询面板中
          defaultEditable: true,
          editable: false,
          formItemProps: {
            rules: [{ required: false, message: '请输入姓名' }],
            componentProps: () => ({
              component: 'Input',
              size: 'small',
            }),
          },
          editFormItemProps: {
            /** 不继承于 `formItemProps`的属性 */
            extendSearchFormProps: false,
            rules: [{ required: false, message: '请输入姓名' }],
          },
        };
        const copy = {};
        $.extend(true, copy, tempItem);
        tempArray.push(copy);
      } else if (cols[i].Style.toLowerCase() == 'combox') {
        const tempItem = {
          title: cols[i].Name,
          dataIndex: cols[i].Field,
          width: cols[i].width,
          resizable: true,
          hideInSearch: cols[i].ifshowInQueryForm ? false : true, //是否生成到最终的查询面板中
          formItemProps: {
            component: 'Select',
            componentProps: ({ tableInstance }) => ({
              options: cols[i].Option,
              size: 'small',
              allowClear: true,
              onChange() {
                console.log('tableInstance', tableInstance?.reload());
              },
            }),
          },
          editable: true,
          defaultEditable: false,
          customRender: ({ record }) => {
            return _getComBoxlabel(record, cols[i]);
          },
        };
        // const copy = deepClone(tempItem);
        const copy = {};
        $.extend(true, copy, tempItem);
        tempArray.push(copy);
      } else if (cols[i].Style.toLowerCase() == 'tree') {
        const tempItem = {
          title: cols[i].Name,
          dataIndex: cols[i].Field,
          width: cols[i].width,
          resizable: true,
          formItemProps: {
            component: 'Select',
            componentProps: ({ tableInstance }) => ({
              size: 'small',
              fieldNames: { label: 'name', value: 'id', options: 'children' },
              mode: cols[i].Mode ? cols[i].Mode : 'combobox',
              options: cols[i].treeOption ? cols[i].treeOption : [],
              allowClear: true,
              onChange() {
                console.log('tableInstance', tableInstance?.reload());
              },
            }),
          },
          editable: true,
          defaultEditable: false,
          customRender: ({ record }) => {
            return _getTreeLabel(record, cols[i]);
          },
          hideInSearch: cols[i].ifshowInQueryForm ? false : true,
        };
        const copy = {};
        $.extend(true, copy, tempItem);
        tempArray.push(copy);
      } else if (cols[i].Style.toLowerCase() == 'checkbox') {
        const tempItem = {
          title: cols[i].Name,
          dataIndex: cols[i].Field,
          width: cols[i].width,
          resizable: true,
          formItemProps: {
            size: 'small',
            component: 'Checkbox',
            componentProps: ({ tableInstance }) => ({
              disabled: !cols[i].isEdit,
              onChange() {
                console.log('tableInstance', tableInstance?.reload());
              },
            }),
          },
          editable: true,
          defaultEditable: false,
          customRender: ({ record }) => {
            return _getCheckBox(record, cols[i]);
          },
          hideInSearch: cols[i].ifshowInQueryForm ? false : true,
        };
        const copy = {};
        $.extend(true, copy, tempItem);
        tempArray.push(copy);
      }
    }
  }
  //生成树形表格
  const _getTreeLabel = (record, col) => {
    const showLabel = getShowName(record, col);
    return getReadOnlyData(showLabel);
  };
  const getReadOnlyData = (data) => {
    return <span>{data}</span>;
  };
  //获取树形表格显示字段
  const getShowName = (record, col) => {
    let label = '';
    let option = [...col.treeOption];
    while (option.length) {
      const target = option.shift();
      if (target.children) {
        if (target.children.length > 0) {
          option = [...option, ...target.children];
        }
      }
      if (target.id == record[col.dataIndex]) {
        label = target.name;
        break;
      }
    }
    return label;
  };
  //定义操作列信息
  const actionItem = {
    title: '操作',
    align: 'center',
    width: 200,
    dataIndex: 'ACTION',
    fixed: 'right',
    actions: ({ record }, action) => {
      const { startEditable, cancelEditable, isEditable, getEditFormModel, validateRow } = action;
      return isEditable(record.FormularId)
        ? [
            {
              label: '保存',
              onClick: async () => {
                const result = await validateRow(record.id);
                message.loading({ content: '保存中...', key: record.FormularId });
                console.log('result', result);
                console.log('保存', getEditFormModel(record.FormularId));
                await waitTime(2000);
                cancelEditable(record.id);
                message.success({ content: '保存成功!', key: record.FormularId, duration: 2 });
              },
            },
            {
              label: '取消',
              onClick: () => {
                cancelEditable(record.FormularId);
              },
            },
          ]
        : [
            {
              label: '编辑',
              onClick: () => {
                startEditable(record.FormularId, record);
              },
            },
          ];
    },
  };

  tempArray.push(actionItem);

  return tempArray;
};

await getAndCols(); //获取列配置文件

export const columns = showCols;
