import React, { useEffect, useRef, useState } from 'react';
import { Card, Modal, Button, Divider, message } from 'antd';
import { connect, useRequest } from "umi";
import AutoTable from '@/components/AutoTable';
import getPrem from '@/utils/getPrem';//权限判断fn
import InitForm from '@/components/InitForm';
import defaultFields from './fields'
import { doFetch } from '@/utils/doFetch';
import { bmNoType } from '@/services/system';

let Rule = (props) => {
  const actionRef = useRef();
  const [vs, cvs] = useState(false),//表单显/隐
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({});

  const { run, loading } = useRequest(doFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      if (result.code == "0000") {
        actionRef.current.reload();
        cvs(false);
      }
    }
  })

  const columns = [
    {
      "title": "单号类型",
      "dataIndex": "noTypeName",
      "key": "noTypeId",
      "options": {
        "database": bmNoType,
        "params": {}
      },
      valueType: "select"
    },
    {
      "title": "预览",
      "dataIndex": "ruleNames",
      "key": "ruleNames",
      "search": false
    },
    {
      title: '操作',
      valueType: 'option',
      width: 155,
      render: (text, row, s, action) => extraAction(text, row, s, action)
    },
  ];

  function extraAction(text, record, s, action) {
    return [
      getPrem("bmNumberRule_save", action, "修改", () => {
        doFetch({ url: "/ngic-base-business/bmNumberRule/queryByNoTypeId", params: { noTypeId: record.id } }).then(res => {
          let row = res?.data?.data;
          ciftype({
            val: "edit",
            id: record.id,
            title: "修改编号规则"
          })
          cf((fields) => {
            for (let i in fields) {
              fields[i].value = row[i];
              fields.noTypeId.options.database = bmNoType;
              fields.noTypeId.disabled = true;
              if (i == "nrList") {
                let reshow = {
                  value: row[i].filter(it => it.noRuleCode != "increasing_order"),
                  other: row[i].filter(it => it.noRuleCode == "increasing_order")[0] || {}
                }
                reshow.other.increaseList = reshow.other.increaseList.map(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;

                fields[i].value = reshow
              }
            }
            return { ...fields }
          });
          cvs(true);
        })

      }),
      getPrem('bmNumberRule_deleteByNoTypeId', action, "删除", null, {
        title: "确认删除该编号规则？",
        onConfirm: () => {
          run({ url: "/ngic-base-business/bmNumberRule/deleteByNoTypeId", params: { noTypeId: record.id } });
        }
      })
    ]
  }

  let saveData = (values, fn) => {
    let newvalues = JSON.parse(JSON.stringify(values));
    let nrList = newvalues.nrList;
    let submitnolist = nrList.value,
      other = nrList.other;

    if (other.sort) {
      submitnolist.splice(other.sort, 0, other);
    } else {
      submitnolist.push(other);
    }


    submitnolist = submitnolist.map((it, i) => {
      return {
        ...it,
        sort: i + 1
      }
    })


    submitnolist = submitnolist.map((it, i) => {
      if (it.noRuleCode == "increasing_order") {
        it.increaseList = it.increaseList.map(item => {
          return submitnolist.filter(itemz => itemz.id == item)[0].sort
        })
      }
      return {
        ...it
      }
    })


    let newfields = {
      ...newvalues,
      nrList: submitnolist
    }

    let difrid = iftype.val == "edit" ? { id: iftype.id } : {};
    run({ url: "/ngic-base-business/bmNumberRule/save", params: { ...newfields, ...difrid } });

  }


  let extra = (<Button disabled={!getPrem("bmNumberRule_save", "ifs")} type="primary" onClick={() => {
    cvs(true);
    cf(fields => {
      for (let i in fields) {
        fields[i].value = null;
        fields[i].disabled = false;

      }
      return { ...fields }
    });
    ciftype({
      val: "add",
      title: "新增编号规则"
    })
  }}>新增</Button>)

  return (
    <div>
      <AutoTable
        columns={columns}
        actionRef={actionRef}
        pagetitle={props.route.name}
        pageextra={extra}
        path="/ngic-base-business/bmNumberRule/queryList"
        pagination="false"
      ></AutoTable>


      <Modal
        maskClosable={false}
        title={iftype.title}
        visible={vs}
        onCancel={() => cvs(false)}
        footer={false}
        destroyOnClose={true}
        width={1200}
      >
        <InitForm
          fields={fields}
          submitData={(values, fn) => {
            saveData(values, fn)
          }}
          onChange={(changedValues, allValues) => {
          }}
          submitting={
            loading || !vs
          }
        >
        </InitForm>
      </Modal>
    </div>
  )
}

export default Rule;