<template>
  <a-spin :spinning="!inited">
    <div :class="$style.projectNodeDiv">
      <sd-form :init-values="[]"
      >
        <template>
          <a-table
              :key="tableData.tableRef"
              :columns="tableData.columns"
              :data-source="projectNodes"
              children-column-name="details"
              :pagination="false"
              row-key="id"
              :default-expand-all-rows="true"
          >
            <template slot="require" slot-scope="text, record">
              <template v-if="record.details && record.details.length">
                <span :class="$style.stepName">{{ record.name }}</span>
              </template>
              <template v-else>
                <span :class="getRequiredClass(record.required)"></span>
                <template v-if="editable">
                  <template v-if="record.required === 'PROJECT_BX'">
                    <a-checkbox disabled checked>
                      {{ getRequiredLabel(record.required) }}
                    </a-checkbox>
                  </template>
                  <template v-else>
                    <a-checkbox
                        :checked="record.requiredChecked === 1"
                        @change="
                      (evt) => {
                        onChangeRequired(evt, record)
                      }
                    "
                    >
                      <!-- {{ getRequiredLabel(record.required) }} -->默认
                    </a-checkbox>
                  </template>
                </template>
                <template v-else>
                  {{ getRequiredLabel(record.required) }}
                </template>
              </template>
            </template>
            <template slot="status" slot-scope="text, record">
              <template v-if="record.details"></template>
              <template v-else>
                <span :class="getStatusClass(record.nodeStatus)"></span>
                <template v-if="editable">
                  <a-select v-model="record.nodeStatus" :options="opts.status"></a-select>
                </template>
                <template v-else>
                  {{ getStatusLabel(record.nodeStatus) }}
                </template>
              </template>
            </template>
            <template slot="maintainUsers" slot-scope="text, record">
              <template v-if="record.details"></template>
              <template v-else>
                <template v-if="editable">
                  <!-- <a-input
                    :read-only="true"
                    :value="
                      getMaintainUsers(record)
                        .map((item) => {
                          return item.name
                        })
                        .join(',')
                    "
                    @click="modifyUser(record)"
                  >
                    <a-icon slot="addonAfter" type="user" @click="modifyUser(record)" />
                  </a-input> -->
                  <a-input :read-only="true" :value="getName(record)" @click="modifyUser(record)">
                    <a-icon slot="addonAfter" type="user" @click="modifyUser(record)"/>
                  </a-input>
                  <!-- <a-button @click="modifyUser(record)">选择</a-button> -->
                </template>
                <template v-else>
                  <sd-user-item :users="getMaintainUsers(record)"/>
                </template>
              </template>
            </template>
            <template slot="startTime" slot-scope="text, record, index, aa">
              <template v-if="record.details"></template>
              <template v-else>
                <template v-if="editable">
                  <a-date-picker
                      :disabled-date="
                    (val) => {
                      return disabledDate(val, record, 'startTime')
                    }
                  "
                      :default-value="toMoment(record.startTime)"
                      @change="
                    (val) => {
                      changeDate(val, record, 'startTime')
                    }
                  "
                  />
                </template>
                <template v-else>
                  {{ record.startTime | sdDateFormat('YYYY-MM-DD') }}
                </template>
              </template>
            </template>
            <template slot="endTime" slot-scope="text, record, index, aa">
              <template v-if="record.details"></template>
              <template v-else>
                <template v-if="editable">
                  <a-date-picker
                      :disabled-date="
                    (val) => {
                      return disabledDate(val, record, 'endTime')
                    }
                  "
                      :default-value="toMoment(record.endTime)"
                      @change="
                    (val) => {
                      changeDate(val, record, 'endTime')
                    }
                  "
                  />
                </template>
                <template v-else>
                  {{ record.endTime | sdDateFormat('YYYY-MM-DD') }}
                </template>
              </template>
            </template>
          </a-table>
          <div style="margin-top:20px;text-align:center"
          >
            <a-button v-if="editable" type="primary" @click="saveForm">保存</a-button>
            <a-button style="margin-left: 20px;" @click="close">关闭</a-button>
          </div
          >
        </template>
      </sd-form>
      <a-modal
          v-model="modalData.visible"
          destroy-on-close
          :mask-closable="false"
          :closable="false"
          centered
      >
        <a-table
            :columns="modalData.columns"
            :data-source="modalData.data"
            :pagination="false"
            row-key="id"
        >
        <span slot="action" slot-scope="text, record">
          <a-checkbox
              :checked="record.isAuthority === 1"
              @change="
              (evt) => {
                changeAuthority(evt, record)
              }
            "
          >
          </a-checkbox>
        </span>
        </a-table>
        <a-button slot="footer" @click="modalData.visible = false">关闭</a-button>
      </a-modal>
    </div>
  </a-spin>
</template>

<script>
import Vue from 'vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import {Message, Modal} from 'ant-design-vue'
import systemManage from '@/system-manage/system-manage'
import auditProjectnodeService from '@product/iam/audit/work/projectnode/audit-projectnode-service'
import moment from 'moment'
import components from './_import-components/audit-projectnode-form-import'

const sdDateFormat = Vue.filter('sdDateFormat')
export default {
  name: 'AuditProjectNodeForm',
  metaInfo: {
    title: '项目节点',
  },
  components,
  data() {
    return {
      inited: true,
      editable: false,
      waterMark: systemManage.getFormWaterMark(),
      projectId: '',
      projectStatus: '',
      projectNodes: [],
      opts: {
        status: [
          {
            id: '01',
            label: '未开始',
            value: '01',
          },
          {
            id: '02',
            label: '进行中',
            value: '02',
          },
          {
            id: '03',
            label: '已完成',
            value: '03',
          },
        ],
        nodeStatus: {
          // 状态label
          '01': '未开始',
          '02': '进行中',
          '03': '已完成',
        },
        statusCls: {
          // 状态className
          '01': 'no-start',
          '02': 'going',
          '03': 'finished',
        },
        requiredLabel: {},
        requiredOpts: [],
      },
      tableData: {
        tableRef: 0,
        columns: [
          {
            title: '',
            scopedSlots: {customRender: 'require'},
          },
          {
            title: '状态',
            scopedSlots: {customRender: 'status'},
          },
          {
            title: '阶段',
            dataIndex: 'auditWorkNodeName',
          },
          {
            title: '维护人员',
            scopedSlots: {customRender: 'maintainUsers'},
          },
          {
            title: '开始时间',
            scopedSlots: {customRender: 'startTime'},
          },
          {
            title: '结束时间',
            scopedSlots: {customRender: 'endTime'},
          },
        ],
      },
      modalData: {
        visible: false,
        data: [],
        columns: [
          {
            title: '姓名',
            dataIndex: 'userName',
            width: '260px',
            customRender: (record) => {
              return record.join('；')
            },
          },
          {
            title: '角色',
            dataIndex: 'userType',
          },
          {
            title: '可维护',
            scopedSlots: {customRender: 'action'},
          },
        ],
      },
    }
  },
  computed: {},
  created() {
    const projectId = this.$route.query.projectId
    const projectStatus = this.$route.query.projectStatus
    if (projectId) {
      this.projectId = projectId
    }
    if (projectStatus) {
      this.projectStatus = projectStatus
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    moment,
    getName(record) {
      // 有打开选择页面才判断选择页面，否则按照原逻辑展示
      const userlist = record.userList
      if (userlist) {
        let username = []
        const userType = []
        userlist
            .filter((item) => item.isAuthority === 1)
            .forEach((item) => {
              username = username.concat(item.userName)
              userType.push(item.userType)
            })
        // 姓名去重
        const reslist = []
        username.forEach((item) => {
          if (!reslist.includes(item)) {
            reslist.push(item)
          }
        })
        // 把isAuthority回写
        record.iamNodeUserBeans.forEach((item) => {
          if (userType.includes(item.userType)) {
            item.isAuthority = 1
          } else {
            item.isAuthority = 0
          }
        })
        return reslist.join(',')
      } else {
        // 原逻辑
        return this.getMaintainUsers(record)
            .map((item) => {
              return item.name
            })
            .join(',')
      }
    },
    onChangeRequired(e, record) {
      if (e.target.checked) {
        // record.required = 'PROJECT_MR'
        record.requiredChecked = 1
      } else {
        // record.required = 'PROJECT_JY'
        record.requiredChecked = 0
      }
    },
    disabledDate(val, record, field) {
      if (field === 'endTime') {
        const startValue = record.startTime
        if (!val || !startValue) {
          return false
        }
        return startValue.valueOf() > val.valueOf()
      } else {
        const endValue = record.endTime
        if (!val || !endValue) {
          return false
        }
        return val.valueOf() > endValue.valueOf()
      }
    },
    changeDate(val, record, field) {
      record[field] = val.valueOf()
    },
    toMoment(val) {
      if (val) {
        return this.moment(sdDateFormat(val, 'YYYY-MM-DD'))
      } else {
        return null
      }
    },
    changeAuthority(e, record) {
      if (e.target.checked) {
        record.isAuthority = 1
      } else {
        record.isAuthority = 0
      }
    },
    modifyUser(record) {
      this.modalData.visible = true
      // 重新计算用户展示，相同角色合并起来展示 userName userType
      // 角色数组，如果已存在则不继续追加
      const userType = {}
      const userTypeList = []
      record.iamNodeUserBeans.forEach((item, index) => {
        if (userType[item.userType]) {
          userType[item.userType].userId.push(item.userAccount)
          userType[item.userType].userName.push(item.userName)
          userType[item.userType].isAuthorityList.push(item.isAuthority)
        } else {
          userTypeList.push(item.userType)
          userType[item.userType] = {
            id: index,
            userId: [item.userAccount],
            userName: [item.userName],
            userType: item.userType,
            isAuthorityList: [item.isAuthority],
          }
        }
        if (userType[item.userType].isAuthorityList.includes(1)) {
          userType[item.userType].isAuthority = 1
        } else {
          userType[item.userType].isAuthority = 0
        }
      })

      const userList = []
      userTypeList.forEach((item) => {
        userList.push(userType[item])
      })

      // this.modalData.data = record.iamNodeUserBeans

      // 这种赋值才能进行响应式
      this.$set(record, 'userList', userList)
      // record.userList = userList
      this.modalData.data = record.userList
    },
    getMaintainUsers(record) {
      const obj = {}
      const userAccount = []

      let users = record.iamNodeUserBeans.map((item) => {
        return {
          name: item.userName,
          code: item.userAccount,
          isAuthority: item.isAuthority,
        }
      })
      users = users.reduce((cur, next, index) => {
        if (obj[next.code + index]) {
        } else {
          obj[next.code + index] = true
          if (next.isAuthority === 1 && !userAccount.includes(next.code)) {
            userAccount.push(next.code)
            cur.push(next)
          }
        }
        return cur
      }, [])
      return users
    },
    getRequiredLabel(key) {
      return this.opts.requiredLabel[key]
    },
    getRequiredClass(key) {
      return key
    },
    getStatusLabel(key) {
      return this.opts.nodeStatus[key]
    },
    getStatusClass(key) {
      return this.opts.statusCls[key]
    },
    initData() {
      Promise.all([
        // 获取节点信息
        auditProjectnodeService.getPorjectNodeInfo(this.projectId),
        // 获取阶段字典
        auditProjectnodeService.getDictionary('PROJECT_PHASE'),
        // 获取节点状态字典
        auditProjectnodeService.getDictionary('PROJECT_JDZT'),
        // 用户权限信息获取
        auditProjectnodeService.checkOperatorAuthority(this.projectId),
      ]).then((allRes) => {
        const nodes = allRes[0].data
        const steps = allRes[1].data
        const stepRef = {}
        steps.forEach((item) => {
          stepRef[item.id] = []
        })
        nodes.forEach((item) => {
          stepRef[item.periodCode].push(item)
        })

        steps.forEach((item) => {
          item.details = stepRef[item.id]
        })

        this.projectNodes = steps

        allRes[2].data.forEach((item, index) => {
          this.opts.requiredLabel[item.id] = item.name
          this.opts.requiredOpts[index] = {
            id: item.id,
            label: item.name,
            value: item.id,
          }
        })

        this.editable = allRes[3].data // === 'true'

        ++this.tableData.tableRef
        // this.$refs.projectNodes.
        if (this.projectStatus === '05' || this.projectStatus === '07') {
          this.editable = false
        }
      })
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    saved() {
      Message.success('保存成功', 1).then((res) => {
      })
    },
    // 保存
    saveForm() {
      this.inited = false
      let params = []
      this.projectNodes.forEach((steps) => {
        steps.details = steps.details.map((item) => {
          item.iamNodeUserEntitys = item.iamNodeUserBeans
          return item
        })
        params = params.concat(steps.details)
      })
      auditProjectnodeService.saveProjectNode(params).then(() => {
        this.inited = true
        Message.success('保存成功', 1)
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/webflow/sd-flow-form.scss';

.stepName {
  color: #3f9bff;
}

.project-node-div {
  :global(.buttons_sd-detail-form_common) {
    visibility: hidden;
  }
}
</style>
