<template>
  <sd-form ref="form" :init-values="values" :class="$style.form">
    <template v-slot="{ model, fields }">
      <sd-form-item
        :name="['startTime', 'finishTime']"
        :input-props="[{ placeholder: '请选择开始时间' }, { placeholder: '请选择结束时间' }]"
      />
      <sd-form-item v-if="global" name="trustorName" />
      <sd-form-item v-else name="trustorArr">
        <sd-user-picker
          v-model="model.trustorArr"
          :disabled-keys="disabledKeys"
          :read-only="model.id ? true : false"
          single
          @change="trustArrChange"
        />
      </sd-form-item>
      <a-form-item label="委托方式" class="test">
        <a-radio-group v-model="model.trustTypeStr" @change="typeChange">
          <a-radio
            v-for="(item, index) in fields.trustTypeStr.attr.selectListItem"
            :key="index"
            :value="item.value"
          >
            <span>{{ item.label }}</span>
            <a-tooltip :title="item.tooltip">
              <a-icon :class="$style.circleicon" type="question-circle" />
            </a-tooltip>
          </a-radio>
        </a-radio-group>
        <div v-if="model.trustTypeStr === '1'" :class="$style.all">
          <sd-user-picker
            v-model="model.operators"
            :class="$style.person"
            :disabled-keys="[userInfo.account, model.trustor]"
            single
            @change="operatorsChange"
          />
          <a-checkbox v-model="addExcept">添加例外</a-checkbox>
        </div>
      </a-form-item>
      <sd-table
        v-if="addExcept || model.trustTypeStr === '0'"
        sortable
        :class="$style.table"
        :columns="columns"
        :data-source.sync="dataSource"
        size="middle"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :pagination="false"
        :scroll="{ y: 300 }"
      >
        <span slot="trusteeName" slot-scope="text">{{ text || '不委托' }}</span>
        <div slot="action" slot-scope="text, record">
          <a>
            <a-icon type="sd-trash2" @click="delData([record.key])" />
          </a>
        </div>
        <template slot="footer">
          <div :class="$style.buttonList">
            <a-button
              v-for="(item, index) in buttonList"
              :key="index"
              type="primary"
              @click="addFlowEntrust(item, index)"
              >添加{{ item.label }}委托</a-button
            >
            <a-button @click="delData(selectedRowKeys)">删除</a-button>
          </div>
        </template>
      </sd-table>
      <sd-form-item name="remark">
        <a-textarea v-model="model.remark" />
      </sd-form-item>
      <sd-form-item name="dataStatusStr" />
    </template>
  </sd-form>
</template>

<script>
import { Message } from 'ant-design-vue'
import moment from 'moment'
import pickValues from '@/common/services/pick-values'
import storeMixin, { getUserInfo } from '@/common/store-mixin'
import SdEntrustAdd from '../myenturst/sd-entrust-add.vue'
import components from './_import-components/sd-setting-page-import'

const columns = [
  {
    dataIndex: 'trustModeName',
    title: '委托方式',
    width: '150px',
  },
  {
    dataIndex: 'trustObjectName',
    title: '委托名称',
  },
  {
    dataIndex: 'trusteeName',
    title: '被委托人',
    width: '150px',
    scopedSlots: { customRender: 'trusteeName' },
  },
  {
    dataIndex: 'action',
    width: '100px',
    scopedSlots: { customRender: 'action' },
  },
]
columns.forEach((item) => {
  item.align = 'center'
})
export default {
  name: 'SdSettingPage',
  metaInfo: {
    title: 'SdSettingPage',
  },
  components,
  mixins: [storeMixin],
  props: {
    global: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      columns,
      partDataSource: [],
      allDataSource: [],
      trustType: '0',
      addExcept: false,
      selectedRowKeys: [],
      buttonList: [
        { label: '流程', value: 'flow' },
        { label: '申请部门', value: 'department' },
        { label: '模块', value: 'businessType' },
      ],
      trustorUser: [],
      values: [
        {
          name: 'id',
          caption: 'ID',
          dataType: 'id',
          required: true,
          readonly: true,
          attr: {
            controlType: 'NumberType',
            field: 'id',
            mandatory: 'true',
          },
        },
        {
          name: 'dataStatusStr',
          caption: '状态',
          required: true,
          dataType: 'selectlist',
          value: '1',
          attr: {
            displayValue: '启用',
            controlType: 'DictType',
            selectListItem: [
              { label: '启用', value: '1' },
              { label: '停用', value: '0' },
            ],
          },
        },
        {
          name: 'startTime',
          caption: '时间',
          required: true,
          dataType: 'date',
          attr: {
            showTime: 'true',
          },
        },
        {
          name: 'finishTime',
          caption: '时间2',
          required: true,
          dataType: 'date',
          attr: {
            showTime: 'true',
          },
        },

        {
          name: 'trustor',
          caption: '委托账号',
          required: true,
          dataType: 'string',
          value: this.global ? getUserInfo().account : '',
        },
        {
          name: 'trustee',
          caption: '受托人账户',
          dataType: 'string',
        },
        {
          name: 'trusteeName',
          caption: '受托人姓名',
          dataType: 'string',
        },
        {
          name: 'trustorName',
          caption: '委托人',
          dataType: 'string',
          readonly: this.global,
          required: true,
          value: this.global ? getUserInfo().name : '',
        },
        {
          name: 'trustTypeStr',
          caption: '委托方式',
          required: true,
          dataType: 'selectlist',
          value: '0',
          attr: {
            displayValue: '部分委托',
            controlType: 'DictType',
            selectListItem: [
              {
                label: '部分委托',
                value: '0',
                tooltip: '设置不同委托场景，同一条委托数据优先匹配排列靠前的受托人。',
              },
              {
                label: '全部委托',
                value: '1',
                tooltip:
                  '设置将所有业务委托给同一受托人，添加例外可单独设置特殊委托场景，同一条数据系统优先匹配例外里的受托人。',
              },
            ],
          },
        },
        {
          name: 'trustorArr',
          caption: '委托人',
          dataType: 'selectperson',
          required: true,
          attr: {
            selectionType: 'USER',
          },
        },
        {
          name: 'operators',
          caption: '被委托人',
          dataType: 'selectperson',
          required: true,
          attr: {
            selectionType: 'USER',
          },
        },
        { name: 'remark', caption: '备注', dataType: 'string' },
      ],
    }
  },
  computed: {
    dataSource: {
      get() {
        return this.trustType === '0' ? this.partDataSource : this.allDataSource
      },
      set(val) {
        if (this.trustType === '0') this.partDataSource = val
        else this.allDataSource = val
      },
    },
    disabledKeys() {
      return [
        this.$refs.form?.getFieldValue('trustee'),
        ...this.dataSource.map((item) => item.trustee),
      ]
    },
  },
  methods: {
    typeChange(e) {
      this.trustType = e.target.value
    },
    setFieldsValue(values) {
      this.trustType = values.trustTypeStr
      this.dataSource = (values.trustDetailBeans || []).map((item) => {
        item.key = item.id + new Date().getTime()
        return item
      })
      this.addExcept = this.trustType === '1' && this.allDataSource.length > 0
      const newValuesInfo = this.values
        .map((item) => item.name)
        .reduce((total, r) => {
          total = {
            ...total,
            [r]: ['startTime', 'finishTime'].indexOf(r) > -1 ? moment(values[r]) : values[r],
          }
          return total
        }, {})
      if (!this.global && values.trustorName && values.trustor) {
        this.$nextTick(() => {
          this.$refs.form.setFieldValue('trustorArr', [
            { type: 'User', name: values.trustorName, code: values.trustor },
          ])
        })
      }
      this.$refs.form.setFieldsValue(newValuesInfo)
    },
    validateFields() {
      const trustTypeStr = this.$refs.form.getFieldValue('trustTypeStr')
      const operators = this.$refs.form.getFieldValue('operators')
      if (trustTypeStr === '1' && !operators?.length) {
        Message.warning('请选择被委托人')
        // eslint-disable-next-line prefer-promise-reject-errors
        return Promise.reject()
      }
      return this.$refs.form.validateFields()
    },
    getBackendValues() {
      const formInfo = this.$refs.form.getBackendValues().reduce((res, item) => {
        res = { ...res, [item.name]: item.value }
        return res
      }, {})
      if (this.dataSource?.length) {
        this.dataSource.forEach((item, index) => {
          item.priorityLevel = index + 1
        })
      }
      delete formInfo.operators
      delete formInfo.trustorArr
      formInfo.trustDetailBeans = [...this.dataSource]
      return formInfo
    },
    delData(keys) {
      this.dataSource = this.dataSource.filter((item) => keys.indexOf(item.key) === -1)
      this.selectedRowKeys = []
    },
    addFlowEntrust(item, index) {
      pickValues(SdEntrustAdd, {
        mode: index,
        trustor: this.$refs.form.getFieldValue('trustor'),
      }).then((res) => {
        if (res) {
          this.dataSource = [...res, ...this.dataSource]
        }
      })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    operatorsChange(value) {
      this.$refs.form.setFieldsValue({
        trustee: value.length ? value[0].code : '',
        trusteeName: value.length ? value[0].name : '',
      })
    },
    trustArrChange(value) {
      this.$refs.form.setFieldsValue({
        trustor: value.length ? value[0].code : '',
        trustorName: value.length ? value[0].name : '',
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
$icon-size: 14px;
.button-list {
  display: flex;
  justify-content: space-around;
}
.all {
  display: flex;
  align-items: center;
  float: right;
  .person {
    min-width: 200px;
    margin-right: 20px;
  }
  > :global(.ant-checkbox-wrapper) {
    min-width: 140px;
  }
}
.table {
  margin-bottom: 20px;
  :global .ant-table-header {
    /* stylelint-disable-next-line  */
    overflow-y: hidden !important;
  }
  :global .ant-table-body {
    overflow-x: hidden;
  }
  :global .anticon-setting {
    display: none;
  }
}
.form {
  > :global(.ant-form-item) {
    &:global(.sd-readonly) {
      margin-bottom: 24px;
    }
  }
  .circleicon {
    margin-left: 10px;
    font-size: $icon-size;
  }
}
</style>
