<template>
  <div :class="$style.searchdiv">
    <a-card :class="$style.searchWrap">
      <a-form-model
        ref="advancedSearchForm"
        :class="$style.antAdvancedSearchForm"
        :model="form"
        layout="horizontal"
        v-bind="formItemLayout"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="案件名称">
              <a-input v-model="form.CASE_NAME"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="案号">
              <a-input v-model="form.CASE_NO" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="案件类型">
              <sd-select v-model="form.CASE_TYPE" :options="caseTypeOptions" :allow-clear="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="我方地位">
              <sd-select
                v-model="form.OWNER_POSITION"
                :options="owerOptions"
                :allow-clear="true"
                @change="selectChanged"
              />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12" :class="$style.amountNum">
            <a-form-model-item label="涉案金额（元）">
              <a-input-number v-model="form.CASE_AMOUNT_S" style="width: 47%"></a-input-number>至
              <a-input-number v-model="form.CASE_AMOUNT_E" style="width: 47%"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="立案日期">
              <a-range-picker
                v-model="form.CASE_DATE"
                style="width: 100%"
                :time-range.sync="form.CASE_DATE"
              />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="16"> </a-col>
          <a-col :class="$style.searchbutton" :span="8">
            <div class="reportbuttonContent" style="margin-right: 15%">
              <a-button @click="handleReset"> 重置 </a-button>
              <a-button type="primary" @click="handleSearch"> 查询 </a-button>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card class="reporttablecardxm">
      <sd-data-table
        ref="sjzlTable"
        :filter-expressions="expressions"
        :columns="columns"
        data-url="api/xcoa-mobile/v1/casefinishedQueryController/getCasefinishedList"
        :process-req="processReq"
        :show-advance-query="false"
        :defultpagination-pagesize="50"
        @dataLoaded="dataLoaded"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="action" slot-scope="text, record">
          <a-button type="link" @click="openMm(record)"
            ><a class="opt-btn_sd-data-table_common">查看</a>
          </a-button>
          <a-button v-show="mmflag" type="link" @click="openCreatAlk(record)"
            ><a class="opt-btn_sd-data-table_common">创建案例库</a></a-button
          >
        </template>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import { router } from '@/common/router-ready'
import auditAdvancedQueryMixins from '../../../components/audit-advanced-query-mixins'
import LawService from '../../law-service'
import components from './_import-components/law-case-finished-query-import'
import { getUserInfo } from '@/common/store-mixin'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
export default {
  name: 'LawCaseFinishedQuery',
  metaInfo: {
    title: '已结案件',
  },
  components: {
    ...components,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      mmflag: false,
      expressions: [],
      caseTypeOptions: [],
      owerOptions: [],
      caseStatusOptions: [],
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '案件名称',
          dataIndex: 'CASE_NAME',
          sorter: true,
        },
        {
          title: '上报单位',
          dataIndex: 'REPORT_UNIT_NAME',
        },
        {
          title: '案件类型',
          dataIndex: 'CASE_TYPE',
          sorter: true,
          width: '150px',
        },
        {
          title: '我方诉讼地位',
          dataIndex: 'OWNER_POSITION',
          scopedSlots: { customRender: 'OWNER_POSITION' },
          sorter: true,
        },

        {
          title: '最终结案方式',
          dataIndex: 'FINISH_TYPE',
          width: '150px',
        },
        {
          title: '胜诉或败诉',
          dataIndex: 'FINISH_RESULT',
          width: '125px',
        },

        {
          title: '结案金额',
          dataIndex: 'FINISH_AMOUNT',
          width: '100px',
        },
        {
          title: '减损金额',
          dataIndex: 'LOSE_AMOUNT',
          width: '100px',
        },

        {
          dataIndex: 'Id',
          sdHidden: true,
          sorter: true,
          defaultSortOrder: 'desc',
        },
        {
          title: '操作',
          dataIndex: '',
          scopedSlots: { customRender: 'action' },
          align: 'center',
        },
      ],

      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      },
      form: {
        OWNER_POSITION: '',
      },
    }
  },
  created() {
    // 获取案件类型
    LawService.getdict('272818597314232320').then((res) => {
      const dict = []
      res.data.forEach((d) => {
        dict.push({
          name: d.label,
          id: d.value,
          disabled: false,
        })
      })
      this.caseTypeOptions = [...dict]
    })
    // 获取我方地位
    LawService.getdict('272888833908473856').then((res) => {
      const dict = []
      res.data.forEach((d) => {
        dict.push({
          id: d.value,
          name: d.label,
          disabled: false,
        })
      })
      this.owerOptions = [...dict]
    })

    //  判断用户是否拥有角色
    LawService.isUserHasRole(getUserInfo().account, 'G-1_LAW_LEADER').then((res) => {
      if (res.data) {
        this.mmflag = true
      }
    })
  },
  mounted() {},
  methods: {
    moment,
    // 获取流程实例的当前活动环节信息
    selectChanged(item) {},
    openCreatAlk(record) {
      window.open(
        '#/sd-flow-guide?moduleId=272154534334758912&finishId=' +
          record.ID +
          '&caseId=' +
          record.CASE_ID
      )
    },

    handleSearch() {
      this.$refs.advancedSearchForm.validate((valid, values) => {
        if (valid) {
          this.search(this.form)
        }
      })
    },
    handleReset() {
      this.$refs.advancedSearchForm.resetFields()
      this.form = {}
      this.search(this.form)
    },

    dataLoaded(eventData) {
      if (!eventData.data) {
        return
      }
      eventData.data.forEach((item, index) => {
        item.id = index
      })
      return eventData
    },
    // 刷新列表
    refresh() {
      this.$refs.sjzlTable.refresh()
    },
    // 查询
    search(form) {
      // 默认查询条件
      this.expressions = []
      // 案件名称
      if (form.CASE_NAME) {
        this.expressions.push({
          dataType: 'str',
          name: 'CASE_NAME',
          op: 'like',
          stringValue: '%' + form.CASE_NAME + '%',
        })
      }
      // 案件类型
      if (form.CASE_TYPE) {
        if (form.CASE_TYPE.length > 0) {
          this.expressions.push({
            dataType: 'str',
            name: 'CASE_TYPE',
            op: 'in',
            stringValue: form.CASE_TYPE.map((item) => {
              return item.id
            }).join(','),
          })
        }
      }
      // 案号
      if (form.CASE_NO) {
        if (form.CASE_NO.length > 0) {
          this.expressions.push({
            dataType: 'str',
            name: 'CASE_TYPE',
            op: 'eq',
            stringValue: form.CASE_NO,
          })
        }
      }

      // 我方地位
      if (form.OWNER_POSITION) {
        if (form.OWNER_POSITION.length > 0) {
          this.expressions.push({
            dataType: 'str',
            name: 'OWNER_POSITION',
            op: 'in',
            stringValue: form.OWNER_POSITION.map((item) => {
              return item.id
            }).join(','),
          })
        }
      }

      // 立案日期
      if (form.CASE_DATE) {
        if (form.CASE_DATE.length > 0) {
          if (form.CASE_DATE[0]) {
            var startYear = new Date(form.CASE_DATE[0].format('YYYY-MM-DD') + ' 00:00:00')
            this.expressions.push({
              dataType: 'str',
              name: 'CASE_DATE',
              op: 'ge',
              stringValue: startYear.getTime(),
            })
          }
          if (form.CASE_DATE[1]) {
            var endYear = new Date(form.CASE_DATE[1].format('YYYY-MM-DD') + ' 23:59:59')
            this.expressions.push({
              dataType: 'str',
              name: 'CASE_DATE',
              op: 'le',
              stringValue: endYear.getTime(),
            })
          }
        }
      }

      // 涉案金额
      if (form.CASE_AMOUNT_S) {
        this.expressions.push({
          dataType: 'str',
          name: 'CASE_AMOUNT',
          op: 'ge',
          stringValue: form.CASE_AMOUNT_S,
        })
      }
      if (form.CASE_AMOUNT_E) {
        this.expressions.push({
          dataType: 'str',
          name: 'CASE_AMOUNT',
          op: 'le',
          stringValue: form.CASE_AMOUNT_E,
        })
      }
    },
    clickRow(record) {
      const url = '/sd-webflow/done-pages/' + record.instId
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },

    processReq(req) {
      req.data = {
        ...req.data,
        formId: 'onlhead:6d9b334e035840fba7843dbdccfd6862',
      }
      return req
    },
    openMm(record) {
      LawService.getProgressData(record.CASE_ID).then((res1) => {
        this.openlastpage(res1.data, record.CASE_ID)
      })
    },

    openlastpage(data, id) {
      const obj = data.at(-1)
      let url = ''
      if (obj.props.stepType === 'progress') {
        // 进展
        if (obj.children && obj.children.length > 0) {
          const zobj = obj.children.at(-1)
          if (zobj.props.detailUrl && zobj.props.detailUrl !== '') {
            url = this.fngetobjurl(zobj, id)
          } else {
            if (zobj.children && zobj.children.length > 0) {
              const zcobj = zobj.children.at(-1)
              if (zcobj.props.detailUrl && zcobj.props.detailUrl !== '') {
                url = this.fngetobjurl(zcobj, id)
              }
            }
          }
        }
      } else if (obj.props.stepType === 'execute') {
        if (obj.children && obj.children.length > 0) {
          const zobj = obj.children.at(-1)
          if (zobj.props.detailUrl && zobj.props.detailUrl !== '') {
            url = this.fngetobjurl(zobj, id)
          }
        }
      } else {
        if (obj.props.detailUrl && obj.props.detailUrl !== '') {
          url = this.fngetobjurl(obj, id)
        }
      }
      if (url === '') {
        url = this.fngetobjurl(data[0], id)
      }
      this.open(url)
    },
    fngetobjurl(obj, id) {
      let url = ''
      url = obj.props.detailUrl + '/' + obj.props.detailInstid
      const page = '/case-progress-page'
      url = url.replace('#/sd-webflow', page)
      url = url + '?zt=' + obj.props.stepType + '&id=' + id // 打开结案页面
      return url
    },
    open(url) {
      const query = {}

      url = url + '&view=1'

      const oRoute = router.resolve({
        path: url,
        query: {
          ...query,
        },
      })

      window.open(oRoute.href, '_blank')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.toptitle {
  margin-left: calc(50% - 150px);
  font-size: 22px;
  font-weight: bold;
  color: #404040;
}
.search-wrap {
  margin-bottom: $padding-lg;
  :global(.ant-advanced-search-form) {
    padding: 0;
    background: transparent;
    border: none;
  }
  :global .ant-divider-horizontal {
    margin: 10px 0;
  }
}
.searchdiv {
  height: 100%;
  :global(.sd-has-table.ant-card) {
    min-height: 50%;
  }
  :global(.reporttablecardxm) {
    :global(.ant-table-body) {
      height: auto !important;
      min-height: auto !important;
      overflow: auto;
    }
  }
  :global(.ant-table-placeholder) {
    height: auto !important;
  }
  :global(.ant-form-item) {
    :global(.ant-form-item-label):first-child {
      width: 200px;
    }
  }
  .amount-num {
    :global(.ant-input-number) {
      width: 15%;
    }
  }
}
</style>
