<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <audit-advanced-query
        :expand="expand"
        :search-data="searchData"
        :ref-name="searchform"
        :search-style="{ height: '150px', left: '20px', top: '57px' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
      >
        <!-- 插槽放置搜索内容 -->
        <template>
          <!-- code name -->
          <!-- <a-col :span="12">
            <a-form-model-item :label="'领域编号'" prop="code">
              <a-input v-model="searchData.code" allow-clear />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-model-item :label="'领域名称'" prop="name">
              <a-input v-model="searchData.name" allow-clear />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <a-card>
        <SdDataTableEx
          ref="sddataTable"
          :form-id="formId"
          :page-id="pageId"
          :data-url="dataUrl"
          :columns="columns"
          :actions="actions"
          :filter-expressions="expressions"
          show-selection
          :search-fields="['code', 'name']"
          :show-advance-query="true"
          @searchbtnClick="searchbtnClick"
        >
          <!-- :check-type="'radio'" -->
          <!-- 表格列 -->
          <template slot="link" slot-scope="text, record">
            <a @click="showFormModal(record.id)">{{ text }}</a>
          </template>
          <!-- 插槽放置表格内容 -->
          <template v-slot:form="{ model }" v-sd-watermark="waterMark" @saved="onSaved">
            <!-- code name description -->
            <SdFormItem name="code" />
            <SdFormItem name="name" />
            <SdFormItem name="description">
              <a-textarea v-model="model.description" />
            </SdFormItem>
          </template>
        </SdDataTableEx>
      </a-card>
      <!-- 人员绑定 -->
      <a-modal title="人员绑定" :visible="visible" @ok="handleOk" @cancel="handleCancel">
        <a-form-model
          ref="ruleFormData"
          layout="horizontal"
          :model="formData"
          :rules="rules"
          v-bind="formItemLayout"
        >
          <a-form-model-item label="领域名称" prop="domainName">
            <!-- <a-input v-model="formData.domainName" :disabled="true"></a-input> -->
            <a-select mode="multiple" :default-value="selectRow" :disabled="true">
              <a-select-option v-for="item in currentRow" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <!-- 公司  -->
          <a-form-model-item label="单位" prop="unitName">
            <SdGroupPicker
              ref="cRelSelect"
              v-model="companyUnit"
              :root-node="userNodeTree"
              :single="true"
              :read-only="false"
              @change="changecompany"
            />
          </a-form-model-item>
          <!-- 整改人 -->
          <a-form-model-item label="整改人" prop="reformUser">
            <a-input v-if="isDisabled" :disabled="true" placeholder="请先选择单位"></a-input>

            <sd-user-picker
              v-else
              ref="peopleRelSelect"
              v-model="reformUserValue"
              :single="false"
              :read-only="false"
              :root-node="rootNode"
              @change="reformUserChange"
            />
          </a-form-model-item>
          <!-- 初审人 -->
          <a-form-model-item label="初审人" prop="checker">
            <a-input v-if="isDisabled" :disabled="true" placeholder="请先选择单位"></a-input>

            <sd-user-picker
              v-else
              ref="peopleRelSelect"
              v-model="checkerValue"
              :single="false"
              :read-only="false"
              :root-node="rootNode"
              @change="checkerValueChange"
            />
          </a-form-model-item>
          <!-- 复审人 -->
          <a-form-model-item label="复审人" prop="reviewer">
            <a-input v-if="isDisabled" :disabled="true" placeholder="请先选择单位"></a-input>

            <sd-user-picker
              v-else
              ref="peopleRelSelect"
              v-model="reviewerValue"
              :single="false"
              :read-only="false"
              :root-node="rootNode"
              @change="reviewerValueChange"
            />
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </div>
  </div>
</template>

<script>
// 筛选组件
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
// 表格组件 + 表格扩展组件
import SdDataTableEx from '@/common/components/sd-data-table-ex.vue'
// 表格按钮类型
import TableActionTypes from '@/common/services/table-action-types'
// 表格工具
import TableColumnTypes from '@/common/services/table-column-types'
import SdFormItem from '@/common/components/sd-form-item.vue'
import components from './_import-components/audit-area-list-import'
import { message } from 'ant-design-vue'
import sdUserPicker from '@/common/components/sd-user-picker.vue'
import SdGroupPicker from '@/common/components/sd-group-picker.vue'
import auditModelService from '../model/audit-model-service'
import auditMaintainService from './audit-maintain-service'
import DataService from '../dataUphold/data-config'
import { getUserInfo } from '@/common/store-mixin'
export default {
  // 大驼峰文件名
  name: 'AuditAreaList',
  metaInfo: {
    // 页面标题
    title: '模型领域',
  },
  components: {
    ...components,
    // 引入组件
    SdFormItem,
    SdDataTableEx,
    auditAdvancedQuery,
    sdUserPicker,
    SdGroupPicker,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      // 搜索条件
      searchData: {
        code: '',
        name: '',
      },
      // 搜索接口传参
      expressions: [],
      // 搜索组件ref
      searchform: 'searchform',
      // 搜索条件展开
      expand: false,
      // 列表请求地址
      dataUrl: 'api/xcoa-mobile/v1/iam-page/businessList',
      // pageId
      pageId: 'audit/maintain/iamModelDomain',
      // formId
      formId: 'iamModelDomain',

      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        //  code name description
        {
          title: '领域编号',
          // dataIndex: 'id',
          dataIndex: 'code',
        },
        {
          title: '领域名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'link' },
        },
        {
          title: '创建时间',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
        },
        {
          title: '领域描述',
          dataIndex: 'description',
        },
      ],
      // 按钮
      actions: [
        {
          label: '新增',
          id: 'create',
          permission: 'create',
          type: TableActionTypes.primary,
          callback: this.showFormModal,
        },
        { label: '关联人员', permission: null, callback: this.bindPeople },
        // 删除
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        },
      ],
      // 表单提交地址
      pagePath: 'audit/maintain/iamModelDomain',

      // 人员绑定
      rules: {
        domainName: [{ required: true, message: '请选择领域名称', trigger: 'blur' }],
        // 所有选项不能为空
        unitName: [
          { required: true, message: '请选择单位', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const primary = this.currentRow.map((item) => {
                const params = {
                  domainId: item.id,
                  unitId: this.formData.unitId,
                }
                return auditMaintainService.checkBind(params)
              })
              Promise.all(primary).then((res) => {
                if (res.some((item) => !item.data)) {
                  // 寻找对应的领域
                  const domain = res
                    .map((item, index) => !item.data && this.currentRow[index].name)
                    .filter((item) => item)
                    .join(',')
                  callback(new Error('当前公司已绑定' + domain))
                } else {
                  callback()
                }
              })
              // .then((res) => {
              //   console.log(res)
              //   if (res.data) {
              //     callback()
              //   } else {
              //     callback(new Error('该单位已绑定'))
              //   }
              // })
              // if (value.length === 0) {
              //   callback(new Error('请选择单位'))
              // } else {
              //   callback()
              // }
            },
            trigger: 'change',
          },
        ],
        reformUser: [{ required: true, message: '请选择整改人', trigger: 'blur' }],
        checker: [{ required: true, message: '请选择初审人', trigger: 'blur' }],
        reviewer: [{ required: true, message: '请选择复审人', trigger: 'blur' }],
      },
      // 人员选择器
      reformUserValue: [],
      checkerValue: [],
      reviewerValue: [],
      rootNode: {},
      companyUnit: null,
      isDisabled: true,
      flag: true,
      visible: false,
      formData: {
        domainId: '',
        domainName: '',
        unitName: '',
        unitId: '',
        reformUser: '',
        reformUserAccount: '',
        checker: '',
        checkerAccount: '',
        reviewer: '',
        reviewerAccount: '',
      },
      // 当前选中的行
      currentRow: [],
      selectRow: [],
      formDetail: null,
      userNodeTree: [],
    }
  },
  computed: {
    formItemLayout() {
      return {
        layout: 'horizontal',
        labelCol: { span: 4 },
        wrapperCol: { span: 18 },
      }
    },
  },
  created() {
    this.initUserCompanyRole()
  },
  methods: {
    initUserCompanyRole() {
      auditMaintainService.getGroup().then((res) => {
        const roleCompany = ['100000', '100001']

        this.userNodeTree = res.data.map((item) => {
          return {
            code: item.id,
            name: item.name,
            type: 'Group',
          }
        })
        if (roleCompany.includes(res.data.code)) {
          this.userNodeTree = []
        }
      })
    },
    // 点击绑定
    bindPeople() {
      // 获取所有选中的数据
      const selectedRows = this.$refs.sddataTable.getSelectedRows()
      if (selectedRows.length === 0) return message.warning('请选择模型领域')
      // 如果大于1条数据，提示 请选择一条数据
      if (selectedRows.length === 1) {
        this.$refs.sddataTable.clearSelection()
        return window.open('#/sd-frame/audit-bind-people?domainId=' + selectedRows[0].id)
      }
      if (selectedRows.length > 1) {
        const allSelect = this.$refs.sddataTable.getSelectedRows()
        this.currentRow = allSelect
        this.selectRow = allSelect.map((item) => item.id)
        this.formData.domainId = allSelect.map((item) => item.id).join(',')
        this.formData.domainName = allSelect.map((item) => item.name).join(',')
        this.visible = true
      }
    },
    // 搜索方法
    handleSearch() {
      // 搜索条件
      const searchDataKeys = Object.keys(this.searchData)
      this.expressions = searchDataKeys.map((item) => {
        return {
          dataType: 'str',
          name: item,
          op: 'like',
          stringValue: `%${this.searchData[item]}%`,
        }
      })
    },
    // 显示表单
    showFormModal(id = null) {
      this.$refs.sddataTable.showDetailModal(id, this.pagePath)
    },

    // 人员绑定
    initFormPage() {},
    // 保存
    handleOk() {
      this.$refs.ruleFormData.validate((valid) => {
        if (valid) {
          const data = this.formData

          auditMaintainService.butchBindPeople(data).then((res) => {
            message.success('保存成功')
            this.$refs.sddataTable.refresh()
            // 清空表单校验
            this.$refs.sddataTable.clearSelection()
            this.handleCancel()
          })
        }
      })
    },
    handleCancel() {
      this.selectRow = []
      this.currentRow = []
      this.reformUserValue = []
      this.checkerValue = []
      this.reviewerValue = []
      this.companyUnit = []
      this.visible = false
      this.isDisabled = true
      this.$refs.ruleFormData.clearValidate()
    },
    // 人员变化事件
    reformUserChange(val) {
      this.reformUserValue = val
      // 序列化人员信息使用,分隔
      const reformUser = val.map((item) => item.name).join(',')
      const reformUserAccount = val.map((item) => item.code).join(',')
      this.formData.reformUser = reformUser
      this.formData.reformUserAccount = reformUserAccount
    },
    checkerValueChange(val) {
      this.checkerValue = val
      const checker = val.map((item) => item.name).join(',')
      const checkerAccount = val.map((item) => item.code).join(',')
      this.formData.checker = checker
      this.formData.checkerAccount = checkerAccount
    },
    reviewerValueChange(val) {
      this.reviewerValue = val
      const reviewer = val.map((item) => item.name).join(',')
      const reviewerAccount = val.map((item) => item.code).join(',')
      this.formData.reviewer = reviewer
      this.formData.reviewerAccount = reviewerAccount
    },
    // 单位变化事件
    changecompany(val) {
      const unitId = val.map((item) => item.code).join(',')
      const unitName = val.map((item) => item.name).join(',')
      this.formData.unitName = unitName
      this.formData.unitId = unitId
      if (val.length > 0) {
        this.isDisabled = false
        this.rootNode = val
      } else {
        this.isDisabled = true
      }
    },
  },
}
</script>

<style lang="scss" module>
@use '@/common/design' as *;
.wrap-height {
  height: 100%;
  .row-height {
    position: relative;
    display: flex;
    flex: auto;
    min-height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
</style>
