<template>
  <a-modal
    :width="1100"
    :visible="visible"
    title="分案"
    destroy-on-close
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div :class="$style.groupstyle">
      <span :class="$style.expandicon" @click="changeexpand('in')">
        <a-icon :type="expandedIn ? 'minus-square' : 'plus-square'" :theme="'filled'" />
        内部代理人
      </span>
    </div>
    <!-- 内部 -->
    <div v-show="expandedIn">
      <sd-data-table-ex
        ref="inTable"
        form-id="lawDivisionIn"
        :columns="columns"
        :filter-expressions="expressions"
        :hide-pagination="true"
        :row-key="'id'"
        :actions="inActions"
      >
        <div slot="divisionDate" slot-scope="text">
          <span>{{ text | sdDateFormat('YYYY-MM-DD ') }}</span>
        </div>
      </sd-data-table-ex>
    </div>
    <div :class="$style.groupstyle">
      <span :class="$style.expandicon" @click="changeexpand('out')">
        <a-icon :type="expandedOut ? 'minus-square' : 'plus-square'" :theme="'filled'" />
        外部代理人
      </span>
    </div>
    <!-- 外部 -->
    <div v-show="expandedOut">
      <sd-data-table-ex
        ref="outTable"
        form-id="lawDivisionOut"
        :columns="columns"
        :filter-expressions="expressions"
        :hide-pagination="true"
        :row-key="'id'"
        :actions="outActions"
      >
        <div slot="divisionDate" slot-scope="text">
          <span>{{ text | sdDateFormat('YYYY-MM-DD ') }}</span>
        </div>
      </sd-data-table-ex>
      <a-modal
        :visible="wvisible"
        :width="900"
        title="添加"
        destroy-on-close
        @ok="outhandleOk"
        @cancel="outhandleCancel"
      >
        <audit-advanced-query
          :expand="expand"
          :search-data="formData"
          :ref-name="searchform"
          :search-style="{ height: '135px', left: '0px', top: '40px' }"
          :search-fun="handleSearch"
          @searchedClick="searchedClick"
        >
          <template>
            <a-col :span="12">
              <a-form-model-item label="姓名" prop="USER_NAME">
                <a-input v-model="formData.USER_NAME" allow-clear />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="所属律所" prop="FIRM_NAME">
                <a-input v-model="formData.FIRM_NAME" allow-clear />
              </a-form-model-item>
            </a-col>
          </template>
        </audit-advanced-query>
        <a-card>
          <sd-data-table-ex
            ref="lawyerTable"
            form-id="onlhead:6c91e5a7ac4c4e099bb4749adaf58381"
            :columns="lawyerColumns"
            :filter-expressions="lawyerExpressions"
            :show-advance-query="true"
            :editnode="false"
            show-selection
            :search-fields="['USER_NAME', 'FIRM_NAME']"
            @searchbtnClick="searchbtnClick"
          >
          </sd-data-table-ex>
        </a-card>
      </a-modal>
    </div>
  </a-modal>
</template>

<script>
import auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import { message } from 'ant-design-vue'
import XmSingleDataService from './xm-single-data-service'
import components from './_import-components/xm-law-sub-case-handler-import'
import TableActionTypes from '@/common/services/table-action-types'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import pickValues from '@/common/services/pick-values'
import TableColumnTypes from '@/common/services/table-column-types'

export default {
  name: 'XmLawSubCaseHandler',
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      divisionType: 'PROGRESS',
      expandedIn: true,
      expandedOut: true,
      caseId: '',
      visible: false,
      wvisible: false,
      expressions: [],
      lawyerExpressions: [],
      searchform: 'searchform',
      lawyerColumns: [
        {
          title: '姓名',
          dataIndex: 'USER_NAME',
        },
        {
          title: '所属律所',
          dataIndex: 'FIRM_NAME',
        },
        {
          title: '账号',
          dataIndex: 'USER_ACCOUNT',
          sdHidden: true,
        },
      ],
      formData: {
        USER_NAME: '',
        FIRM_NAME: '',
      },
      columns: [
        {
          title: '姓名',
          dataIndex: 'agentName',
        },
        {
          title: '分案时间',
          dataIndex: 'divisionDate',
          sdRender: TableColumnTypes.dateTime,
          scopedSlots: { customRender: 'divisionDate' },
        },
        {
          title: '状态',
          dataIndex: 'agentStatus',
          sdHidden: true,
        },
      ],
      inActions: [
        {
          label: '新增',
          id: 'addin',
          type: TableActionTypes.primary,
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            this.addDivision('in')
          },
        },
        {
          label: '停用',
          id: 'instop',
          type: TableActionTypes.inline, // 数据行内的按钮，回调参数为record, {rowIndex}
          hidden(record, rowIndex) {
            // 状态为停用时隐藏
            return record.agentStatus === '1'
          },
          callback: (keys, records) => {
            this.changeStatus('in', keys)
          },
        },
        {
          label: '启用',
          id: 'instart',
          type: TableActionTypes.inline, // 数据行内的按钮，回调参数为record, {rowIndex}
          hidden(record, rowIndex) {
            // 状态为停用时隐藏
            return record.agentStatus === '0'
          },
          callback: (keys, records) => {
            this.changeStatus('in', keys)
          },
        },
      ],
      outActions: [
        {
          label: '新增',
          id: 'outadd',
          type: TableActionTypes.primary,
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            this.addDivision('out')
          },
        },
        {
          label: '停用',
          id: 'outstop',
          type: TableActionTypes.inline, // 数据行内的按钮，回调参数为record, {rowIndex}
          hidden(record, rowIndex) {
            // 状态为停用时隐藏
            return record.agentStatus === '1'
          },
          callback: (keys, records) => {
            this.changeStatus('out', keys)
          },
        },
        {
          label: '启用',
          id: 'outstart',
          type: TableActionTypes.inline, // 数据行内的按钮，回调参数为record, {rowIndex}
          hidden(record, rowIndex) {
            // 状态为停用时隐藏
            return record.agentStatus === '0'
          },
          callback: (keys, records) => {
            this.changeStatus('out', keys)
          },
        },
      ],
    }
  },
  methods: {
    run({ button, eventScript, context: { args, dataList, fieldInfos } }) {
      // 列表筛选
      this.expressions = []
      this.divisionType = eventScript.divisionType // 分案类型，进展/执行
      this.expressions.push({
        dataType: 'str',
        name: 'divisionType',
        op: 'eq',
        stringValue: eventScript.divisionType,
      })
      this.caseId = fieldInfos.find((f) => f.name === 'CASE_ID')?.value // 案件id
      this.expressions.push({
        dataType: 'str',
        name: 'caseId',
        op: 'eq',
        stringValue: this.caseId,
      })
      this.visible = true
    },
    handleOk(e) {
      message.success('保存成功', 1)
      setTimeout(() => {
        this.visible = false
      }, 1000)
    },
    handleCancel(e) {
      this.visible = false
    },
    addDivision(type) {
      // 新增处理人
      switch (type) {
        case 'in':
          // 内部
          this.inAdd()
          break
        case 'out':
          // 外部
          this.outAdd()
          break
        default:
          break
      }
    },
    inAdd() {
      // 新增内部处理人--人员选择组件
      pickValues(
        sdUserPicker, // 第一个参数：使用的选择器组件
        // 第二个参数：传递给选择器的props。默认选中的值、是否单选等，都可以传递
        {
          single: false,
        }
      )
        // 用户选择完成后，promise返回选中的值。用户取消返回undefined
        .then((values) => {
          const params = []
          values.forEach((item) => {
            params.push({
              agentId: '',
              agentCode: item.code,
              agentName: item.name,
              divisionDate: new Date().getTime(),
              agentStatus: '0',
              caseId: this.caseId,
              divisionType: this.divisionType,
            })
          })
          XmSingleDataService.saveLawDivisionIn(params)
            .then((res) => {
              if (res.status === 200) {
                // 刷新列表
                setTimeout(() => {
                  this.$refs.inTable.refresh()
                }, 1000)
              } else {
                message.error('保存失败，请联系管理员')
              }
            })
            .catch((e) => {
              // console.log(e)
              message.error('保存失败，请联系管理员')
            })
        })
    },
    outAdd() {
      // 弹框选择外聘律师
      this.wvisible = true
    },
    outhandleCancel(e) {
      this.wvisible = false
    },
    outhandleOk(e) {
      // 新增外部处理人
      const selrows = this.$refs.lawyerTable.getSelectedRows()
      if (selrows && selrows[0]) {
        const params = []
        selrows.forEach((item) => {
          params.push({
            agentId: '',
            agentCode: item.USER_ACCOUNT,
            agentName: item.USER_NAME,
            divisionDate: new Date().getTime(),
            agentStatus: '0',
            caseId: this.caseId,
            divisionType: this.divisionType,
          })
        })
        XmSingleDataService.saveLawDivisionOut(params)
          .then((res) => {
            if (res.status === 200) {
              // 刷新列表
              setTimeout(() => {
                this.$refs.outTable.refresh()
              }, 1000)
            } else {
              message.error('保存失败，请联系管理员')
            }
          })
          .catch((e) => {
            // console.log(e)
            message.error('保存失败，请联系管理员')
          })
      }
      this.wvisible = false
    },
    // 外聘律师查询
    handleSearch() {
      this.lawyerExpressions.push({
        dataType: 'str',
        name: 'divisionType',
        op: 'eq',
        stringValue: this.divisionType,
      })
      // 姓名
      if (this.formData.USER_NAME) {
        this.lawyerExpressions.push({
          dataType: 'str',
          name: 'USER_NAME',
          op: 'like',
          stringValue: `%${this.formData.USER_NAME}%`,
        })
      }

      // 所属律所
      if (this.formData.FIRM_NAME) {
        this.lawyerExpressions.push({
          dataType: 'str',
          name: 'FIRM_NAME',
          op: 'like',
          stringValue: `%${this.formData.FIRM_NAME}%`,
        })
      }
    },
    changeUserStatusIn(id, agentStatus) {
      const status = agentStatus === '1' ? '0' : '1'
      // 修改内部处理人状态
      XmSingleDataService.changeUserStatusIn(id, status)
        .then((res) => {
          if (res.status === 200) {
            // 刷新列表
            setTimeout(() => {
              this.$refs.inTable.refresh()
            }, 1000)
          } else {
            message.error('操作失败，请联系管理员')
          }
        })
        .catch((e) => {
          // console.log(e)
          message.error('操作失败，请联系管理员')
        })
    },
    changeUserStatusOut(id, agentStatus) {
      const status = agentStatus === '1' ? '0' : '1'
      // 修改外部处理人状态
      XmSingleDataService.changeUserStatusOut(id, status)
        .then((res) => {
          if (res.status === 200) {
            // 刷新列表
            setTimeout(() => {
              this.$refs.outTable.refresh()
            }, 1000)
          } else {
            message.error('操作失败，请联系管理员')
          }
        })
        .catch((e) => {
          // console.log(e)
          message.error('操作失败，请联系管理员')
        })
    },
    changeStatus(type, record) {
      // 修改处理人状态
      switch (type) {
        case 'in':
          this.changeUserStatusIn(record.id, record.agentStatus)
          break
        case 'out':
          this.changeUserStatusOut(record.id, record.agentStatus)
          break
        default:
          break
      }
    },
    changeexpand(type) {
      //  折叠展开
      switch (type) {
        case 'in':
          this.expandedIn = !this.expandedIn
          break
        case 'out':
          this.expandedOut = !this.expandedOut
          break
        default:
          break
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.groupstyle {
  float: left;
  position: relative;
  z-index: 11;
  width: 90%;
  line-height: 40px;
}
.expandicon {
  line-height: 22px;
  cursor: pointer;
  :global .anticon {
    color: #1890ff;
  }
}
</style>
