import qs from 'qs'
import { router } from '@/common/router-ready'
import { Modal, message } from 'ant-design-vue'
import LawService from '../../../../../src_product/iam/law/law-service'

export default function({ button, eventScript, context }) {
  return new Promise((resolve) => {
    const strtype = eventScript.strtype === '1' // true纠纷 否则案件
    // 打开新建页面
    const isNewWindow = eventScript.newWindow === '1'
    console.log(eventScript)
    if (strtype) {
      const strjftype = eventScript.strjftype === '1' // true 进展 否则结案
      LawService.getAlljfStage().then((res) => {
        const stage = []
        res.data.data.forEach((d) => {
          stage.push({
            name: d.STAGE_NAME,
            code: d.STAGE_CODE,
          })
        })
        var s = this
        this.valueChange = function(value) {
          this.stagef = value
        }
        const { fieldInfos } = context
        const jfid = fieldInfos.find((f) => f.name === 'DISPUTE_ID')?.value
        // 判断打开新建页面 还是打开正在处理中的纠纷进展
        LawService.getProgressData(jfid).then((res1) => {
          let flag = true // true 是弹出纠纷登记 false 是不弹出纠纷登记
          let djurl = ''
          let jfjzid = ''
          if (res1.data.length > 1) {
            // 有纠纷登记
            if (res1.data[1].children && res1.data[1].children.length > 0) {
              if (
                res1.data[1].children[res1.data[1].children.length - 1].props.stepStatus === '0'
              ) {
                // 有纠纷登记并且未办结
                djurl =
                  res1.data[1].children[res1.data[1].children.length - 1].props.detailUrl +
                  '/' +
                  res1.data[1].children[res1.data[1].children.length - 1].props.detailInstid
                flag = false
              } else {
                // 有纠纷登记且办结
              }
              jfjzid = res1.data[1].id
            }
          } else {
            // 无纠纷登记 弹出选择阶段名称
          }
          if (flag && strjftype) {
            Modal.confirm({
              title: '请选择阶段名称',
              content: (h) => {
                const info = []
                stage.forEach((s) => {
                  info.push(h('a-select-option', { props: { value: s.code }, key: s.code }, s.name))
                })
                this.stage = stage
                this.stagef = ''

                return h(
                  'a-form-model',
                  { props: { labelCol: { span: 7 }, wrapperCol: { span: 15 } } },
                  [
                    h('a-form-model-item', { props: { label: '阶段名称' }, required: true }, [
                      h(
                        'a-select',
                        {
                          attrs: { model: { value: s.stagef } },
                          on: { change: (e) => s.valueChange(e) },
                        },
                        info
                      ),
                    ]),
                  ]
                )
              },
              okText: '确定',
              okType: 'danger',
              onOk: () => {
                if (this.stagef === '') {
                  Modal.warning({
                    title: '提示',
                    content: '请选择阶段名称',
                  })
                  return false
                } else {
                  // 获取设置的默认值
                  const id = fieldInfos.find((f) => f.name === 'id')?.value
                  // 业务类型
                  const businessTypeId = eventScript.businessTypeId
                  // 模块表单id
                  const appModuleId = eventScript.appModuleId

                  // 打开新建页面
                  const extobj = { moduleId: appModuleId }
                  const ext = qs.stringify('&extParams=' + extobj)
                  const url =
                    '/law-progress-page/pages/draft/0?businessTypeId=' +
                    businessTypeId +
                    ext +
                    '&zt=2&jfid=' +
                    jfid +
                    '&stage=' +
                    this.stagef +
                    '&parentid=' +
                    jfjzid
                  const query = {}
                  const oRoute = router.resolve({
                    path: url,
                    query: {
                      ...query,
                    },
                  })
                  if (isNewWindow) {
                    const s = window.open(oRoute.href, '_blank')
                    s.opener = null
                  } else {
                    router.push(oRoute.route.fullPath)
                  }
                  resolve()
                }
              },
              onCancel() {
                resolve(false)
              },
            })
          } else {
            let zt = '2'
            let url = ''
            if (!strjftype) {
              zt = '3'
              // 判断返回的是否有结案数据，无则打开结案新建页面，否则打开历史
              let jaflag = true // true 新建 false 为打开历史
              if (res1.data.length > 2) {
                if (res1.data[2].props.stepType === 'finish') {
                  jaflag = false
                }
              }
              if (jaflag) {
                // 业务类型
                const businessTypeId = eventScript.businessTypeId
                // 模块表单id
                const appModuleId = eventScript.appModuleId

                // 打开新建页面
                const extobj = { moduleId: appModuleId }
                console.log(extobj)
                const ext = qs.stringify('&extParams=' + extobj)
                console.log(ext)
                url =
                  '/law-progress-page/pages/draft/0?businessTypeId=' +
                  businessTypeId +
                  ext +
                  '&zt=' +
                  zt +
                  '&jfid=' +
                  jfid
              } else {
                url = res1.data[2].props.detailUrl + '/' + res1.data[2].props.detailInstid
                url = url.replace('#/sd-webflow', '/law-progress-page')
                url = url + '?zt=' + zt + '&jfid=' + jfid // 打开结案页面
              }
            } else {
              // 打开正在处理中的文档
              djurl = djurl.replace('#/sd-webflow', '/law-progress-page')
              url = djurl + '?zt=' + zt + '&jfid=' + jfid // 打开登记页面
            }
            const query = {}
            const oRoute = router.resolve({
              path: url,
              query: {
                ...query,
              },
            })

            if (isNewWindow) {
              const s = window.open(oRoute.href, '_blank')
              s.opener = null
            } else {
              router.push(oRoute.route.fullPath)
            }
            resolve()
          }
        })
      })
    } else {
      // 案件 判断目前是 案件进展 案件结案 案件执行？
      const strcasetype = eventScript.strcasetype // 进展1 否则结案2 执行3
      console.log('strcasetype---' + strcasetype)
      // 打开新建页面
      var s = this
      this.selectjd = []
      this.dataList = []
      this.treeData = []
      this.expandedKeys = ['0']
      this.selectedKeys = ['0']
      let parentid = ''
      console.log(eventScript)
      this.onLoadData = function(treeNode) {
        console.log('---1-onLoadData')
        if (treeNode.dataRef.children) return Promise.resolve()
        // let caseType = ''
        // let caseStage = ''
        // if (treeNode.dataRef.props.parentId === 'root') {
        //   caseType = treeNode.dataRef.id
        // } else {
        //   caseType = treeNode.dataRef.props.parentId
        //   caseStage = treeNode.dataRef.id
        // }
        // return LawService.getCaseTree(caseType, caseStage).then((res) => {
        //   res.data.forEach((d) => {
        //     d.props.parentName = treeNode.dataRef.text
        //     d.props.caseType = treeNode.dataRef.props.parentId
        //   })
        //   treeNode.dataRef.children = res.data
        //   // console.log(this.treeData)
        //   return treeNode
        //   // this.treeData = this.transformData([...this.treeData])
        //   // this.generateList(this.treeData)
        // })
      }
      this.transformData = function(data) {
        return data.map((d) => {
          const { children, ...rest } = d
          return {
            ...rest,
            children: children && this.transformData(children),
            scopedSlots: { title: 'title' },
          }
        })
      }
      // 处理搜索用的dataList
      this.generateList = function(data) {
        for (let i = 0; i < data.length; i++) {
          const node = data[i]
          const key = node.id
          const title = node.text
          const props = node.props
          this.dataList.push({ key, id: key, title: title, props })
          if (node.children) {
            if (node.children) {
              node.leaf = true
            }
            this.generateList(node.children)
          }
        }
      }
      this.treeCheck = function(allKeys, echecked) {
        console.log('--1')
      }
      this.onExpand = function(expandedKeys) {
        // 用户点击展开时，取消自动展开效果
        this.expandedKeys = expandedKeys
        this.autoExpandParent = false
      }
      // 拖拽节点方法
      this.onDrop = function(info) {
        // 被插入节点信息
      }

      this.treeSelect = function treeSelect(key, item) {
        console.log('--t')
        console.log(key)
        console.log(item)
        if (
          item.selectedNodes[0].data.props.props.businessTypeId &&
          item.selectedNodes[0].data.props.props.businessTypeId !== ''
        ) {
          console.log(item.selectedNodes[0].data)
          this.selectjd = [
            {
              url: item.selectedNodes[0].data.props.props.pageUrl,
              businessTypeId: item.selectedNodes[0].data.props.props.businessTypeId,
              stage: item.selectedNodes[0].data.props.id,
              stagename: item.selectedNodes[0].data.props.text,
              jdname: item.selectedNodes[0].data.props.props.parentName,
              caseStage: item.selectedNodes[0].data.props.props.parentId,
              caseType: item.selectedNodes[0].data.props.props.caseType,
            },
          ]
        } else {
          this.selectjd = []
        }
      }
      const { fieldInfos } = context
      const caseid = fieldInfos.find((f) => f.name === 'CASE_ID')?.value

      LawService.getProgressData(caseid).then((res1) => {
        console.log(res1)
        let zt = ''
        // 打开列表页面
        if (strcasetype === '1') {
          // 判断进展数据是否有未办结的
          zt = '2'
          let flag = true // true 才新建案件进展，弹出选择树，否则展示进展页面
          let casesburl = ''
          let url = ''
          if (res1.data.length > 1) {
            // 有案件登记
            if (res1.data[1].children && res1.data[1].children.length > 0) {
              if (
                res1.data[1].children[res1.data[1].children.length - 1].props.stepStatus === '0'
              ) {
                // 有案件登记并且未办结
                casesburl =
                  res1.data[1].children[res1.data[1].children.length - 1].props.detailUrl +
                  '/' +
                  res1.data[1].children[res1.data[1].children.length - 1].props.detailInstid
                flag = false
              } else {
                // 有纠纷登记且办结
              }
            }
            parentid = res1.data[1].id
          }
          // 获取设置的默认值
          // const caseid = fieldInfos.find((f) => f.name === 'id')?.value
          // LawService.getAllCaseTree().then((r) => {
          if (flag) {
            LawService.getAllCaseTree().then((r) => {
              const treeNode = [
                {
                  id: '0',
                  text: '阶段',
                  leaf: false,
                  props: {},
                  children: r.data,
                  key: '0',
                },
              ]
              this.treeData = this.transformData(treeNode)
              this.generateList(this.treeData)
              console.log('--数据')
              console.log(this.treeData)
              // 弹出选择树
              Modal.confirm({
                title: '请选择阶段名称',
                content: (h) => {
                  const info = []
                  // stage.forEach((s) => {
                  //   info.push(h('a-select-option', { props: { value: s.code }, key: s.code }, s.name))
                  // })
                  // this.stage = stage
                  // this.selectjd = []
                  // return h('law-case-tree', {
                  //   on: { treeSelect: (key, item) => s.treeSelect(key, item) },
                  // })
                  // const treeData = this.treeData
                  return h('div', null, [
                    h('a-tree', {
                      ref: 'tree',
                      props: {
                        'block-node': false,
                        'show-icon': true,
                        'show-line': true,
                        'check-strictly': true,
                        checkable: false,
                        draggable: false,
                        'tree-data': this.treeData,
                        'replace-fields': {
                          title: 'text',
                          key: 'id',
                        },
                        'expanded-keys': ['0'],
                        'default-expanded-keys': this.expandedKeys,
                        'selected-keys': this.$attrs['selected-keys'] || this.selectedKeys,
                        'load-data': this.onLoadData,
                      },
                      on: {
                        select: this.treeSelect,
                        check: this.treeCheck,
                        expand: this.onExpand,
                        drop: this.onDrop,
                      },
                      // on:{select:this.treeSelect,"update:selectedKeys":t.setSelectedKeys},
                      // on: {
                      //   select: (key, item) => s.treeSelect(key, item),
                      //   check: (e) => s.treeCheck(e),
                      //   expand: (e) => s.onExpand(e),
                      //   drop: (e) => s.onDrop(e),
                      // },
                    }),
                  ])
                },
                okText: '确定',
                okType: 'danger',
                onOk: () => {
                  if (this.selectjd.length === 0) {
                    Modal.warning({
                      title: '提示',
                      content: '请选择案件程序信息',
                    })
                    return false
                  } else {
                    // 获取设置的默认值
                    // 业务类型
                    const businessTypeId = this.selectjd[0].businessTypeId
                    // 模块表单id
                    // const appModuleId = eventScript.appModuleId

                    // 打开新建页面
                    // const extobj = { moduleId: appModuleId }
                    // const ext = qs.stringify('&extParams=' + extobj)
                    const url =
                      '/case-progress-page/pages/draft/0?businessTypeId=' +
                      businessTypeId +
                      '&zt=2&caseid=' +
                      caseid +
                      '&stage=' +
                      this.stagef +
                      '&parentid='
                    const query = {}
                    const oRoute = router.resolve({
                      path: url,
                      query: {
                        ...query,
                      },
                    })
                    if (isNewWindow) {
                      const s = window.open(oRoute.href, '_blank')
                      s.opener = null
                    } else {
                      router.push(oRoute.route.fullPath)
                    }
                    resolve()
                  }
                },
                onCancel() {
                  resolve(false)
                },
              })
            })
          } else {
            // 展示信息

            // 打开正在处理中的文档
            casesburl = casesburl.replace('#/sd-webflow', '/law-progress-page')
            url = casesburl + '?zt=' + zt + '&caseid=' + caseid // 打开登记页面
            const query = {}
            const oRoute = router.resolve({
              path: url,
              query: {
                ...query,
              },
            })

            if (isNewWindow) {
              const s = window.open(oRoute.href, '_blank')
              s.opener = null
            } else {
              router.push(oRoute.route.fullPath)
            }
            resolve()
          }
        } else if (strcasetype === '2') {
          // 结案
        } else {
          // 执行 3
        }
        // 业务类型
        // const businessTypeId = '200800'
        // // 模块表单id
        // const appModuleId = eventScript.appModuleId
        // const zt = '1'
        // // 打开新建页面
        // // let url = res1.data[2].props.detailUrl + '/' + res1.data[2].props.detailInstid
        // // url = url.replace('#/sd-webflow', '/case-progress-page')
        // // url = url + '?zt=' + zt + '&caseid=' + caseid // 打开结案页面
        // //  const extobj = { moduleId: appModuleId }
        // //  const ext = qs.stringify('&extParams=' + extobj)
        // const url =
        //   '/case-progress-page/pages/draft/0?businessTypeId=' +
        //   businessTypeId +
        //   '&zt=2&caseid=' +
        //   caseid +
        //   '&stage=' +
        //   this.stagef +
        //   '&parentid=' +
        //   caseid
        // const query = {}
        // const oRoute = router.resolve({
        //   path: url,
        //   query: {
        //     ...query,
        //   },
        // })
        // if (isNewWindow) {
        //   window.open(oRoute.href, '_blank')
        // } else {
        //   router.push(oRoute.route.fullPath)
        // }
        // resolve()
      })
    }
  })
}
