<template>
  <section class="managementDetail">
    <ai-detail>
      <template #title>
        <ai-title title="公文详情" isShowBottomBorder isShowBack @onBackClick="cancel(true)">
          <template #rightBtn>
            <ai-wechat-selecter :instance="instance" v-model="addUser" :isMultiple="form.readType == '0' ? false : true" @change="onChange" v-if="form.status === '0'">
              <el-button
                size="small"
                type="primary"
                icon="iconfont iconMediaPlayer_Play">
                开始流转
              </el-button>
            </ai-wechat-selecter>
            <ai-wechat-selecter :instance="instance" v-model="addUser" :isMultiple="form.readType == '0' ? false : true" @change="onChange" v-if="form.status === '2' && form.readType == '0'">
              <el-button
                size="small"
                type="primary"
                icon="iconfont iconResetting">
                再次流转
              </el-button>
            </ai-wechat-selecter>
            <el-button
            @click="endCirculation"
            v-if="form.status === '1'"
            size="small"
            icon="iconfont iconReject">
            结束流转</el-button>
          </template>
        </ai-title>
        
      </template>
      <template #content>
        <ai-card :title="form.documentName">
          <template slot="content">
            <ai-wrapper class="mar-t16" label-width="80px" :columnsNumber="3">
              <ai-info-item label="公文编号："><span>{{form.documentCode || '-'}}</span></ai-info-item>
              <ai-info-item label="公文类型："><span>{{$dict.getLabel("officialDocumentName", form.documentType) || '-'}}</span></ai-info-item>
              <ai-info-item label="保密等级："><span>{{$dict.getLabel("officialDocumentConfidentialityLevel", form.confidentialityLevel) || '-'}}</span></ai-info-item>
            </ai-wrapper>
            <ai-wrapper label-width="80px" :columnsNumber="3">
              <ai-info-item label="阅示类型："><span>{{$dict.getLabel("officialDocumentReadType", form.readType) || '-'}}</span></ai-info-item>
              <ai-info-item label="紧急程度："><span>{{$dict.getLabel("officialDocumentEmergencyLevel", form.emergencyLevel) || '-'}}</span></ai-info-item>
              <ai-info-item label="发文机关："><span>{{dict.getLabel('issuingUnit',form.issuingUnit)|| '-'}}</span></ai-info-item>
            </ai-wrapper>
            <ai-wrapper label-width="80px" :columnsNumber="3">
              <ai-info-item label="发文字号："><span>{{form.issuingFont || '-'}}</span></ai-info-item>
              <ai-info-item label="签发人："><span>{{form.signer || '-'}}</span></ai-info-item>
              <ai-info-item label="发文时间："><span>{{form.createTime || '-'}}</span></ai-info-item>
            </ai-wrapper>
            <ai-wrapper label-width="80px" :columnsNumber="1">
              <ai-info-item label="备注："><span>{{form.remark || '-'}}</span></ai-info-item>
            </ai-wrapper>
            <ai-bar title="附件" >
              <template slot="right" v-if="form.files && form.files.length">
                <span class="Edit" @click="downFileAll"><i class="iconfont iconDownload"></i>下载全部</span>
              </template>
            </ai-bar>
            <ai-file-list v-if="form.files && form.files.length"
              :fileList="form.files"
              :fileOps="{ name: 'name', size: 'fileSizeStr' }"
            ></ai-file-list>
          </template>
        </ai-card>
        <ai-card title="流转信息">
          <template #right>
            <ai-wechat-selecter :instance="instance" v-model="addFlow" @change="addPeople" v-if="form.readType==0 && form.status !== '2'">
              <el-button
                size="small"
                type="primary"
                icon="iconfont iconAdd">
                指派人员
              </el-button>
            </ai-wechat-selecter>
          </template>

          <template #content>
            <ai-wrapper
              label-width="70px"
              :columnsNumber="3">
              <ai-info-item label="流转状态："><span :class="'status-' + form.status">{{ dict.getLabel('documentStatus', form.status) }}</span></ai-info-item>
              <ai-info-item label="当前流转对象：" label-width="98px" v-if="form.readType === '0'">{{ form.flowUserName || '-' }}</ai-info-item>
              <ai-info-item></ai-info-item>
            </ai-wrapper>
          </template>
        </ai-card>
        <ai-card title="流转记录">
          <template #right>
            <ai-wechat-selecter :instance="instance" v-model="addFlow" @change="addFlowChange" v-if="form.readType === '1' && (form.status === '1' || form.status === '0') && $permissions('app_appofficialdocumentinfo_edit')">
              <el-button
                size="small"
                type="primary"
                icon="iconfont iconAdd">
                添加人员
              </el-button>
            </ai-wechat-selecter>
          </template>

          <template #content>
            <div class="ai-steps" v-if="form.readType === '0'">
              <div class="ai-steps__item" v-for="(item, index) in form.flowUsers" :key="index">
                <div class="ai-steps__item--left">
                  <div class="ai-steps__item__avatar">
                    <img :src="item.avatar" v-if="item.avatar">
                    <h2 v-else>{{ formatName(item.flowUserName) }}</h2>
                    <i class="iconfont iconSteps_Finished"></i>
                  </div>
                  <div class="ai-steps__item--content">
                    <span>{{ dict.getLabel('documentFlowStatus', item.flowStatus) }}</span>
                    <h2>{{ item.flowUserName }}</h2>
                    <p v-if="item.description">{{ item.description }}</p>
                  </div>
                </div>
                <div class="ai-steps__item--right">{{ item.flowTime }}</div>
              </div>
            </div>
            <ai-table
              class="table"
              v-if="form.readType === '1'"
              :tableData="tableData"
              :col-configs="colConfigs"
              :total="total"
              :isShowPagination="false"
              :current.sync="search.current"
              :size.sync="search.size"
              :border="true">
              <el-table-column slot="options" label="操作" align="center" width="120px">
                <template slot-scope="{ row }">
                  <span
                    v-if="$permissions('app_appofficialdocumentinfo_edit')"
                    class="iconfont iconDelete"
                    title="删除"
                    style="cursor: pointer;"
                    @click="remove(row.id)">
                  </span>
                </template>
              </el-table-column>
            </ai-table>
          </template>
        </ai-card>
      </template>
    </ai-detail>
  </section>
</template>

<script>
export default {
  name: "managementDetail",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
    params: Object
  },
  data() {
    return {
      form: {
        documentName: '',
        documentCode: '',
        documentType: '',
        confidentialityLevel: '',
        readType: '',
        emergencyLevel: '',
        issuingTime: '',
        issuingUnit: '',
        issuingFont: '',
        signer: '',
        overDescription: '',
        overTime: '',
        deliver: '',
        remark: '',
        files: [],
        fileIds: [],
        flowUsers: [],
      },
      isAdd: true,
      isMultiple: true,
      addUser: [],
      addFlow: [],
      tableData: [],
      search: {
        size: 10,
        current: 1
      },
      total: 10,
      colConfigs: [
        { prop: 'flowUserName',  label: '姓名', align: 'center' },
        { prop: 'readTime', label: '时间', align: 'center' },
        {
          prop: 'readStatus',
          label: '阅示情况',
          align: 'center',
          render: (h, params) => {
            return h('span', {
              style: {
                color: params.row.readStatus === '0' ? '#FF8822' : '#2EA222'
              }
            }, this.$dict.getLabel('readingStatus', params.row.readStatus))
          }
        },
        { slot: 'options', label: '操作', align: 'center' }
      ],
    };
  },
  computed: {
    formRules(){
      return {
        documentName: [{required: true, message: "请输入公文名称", trigger: 'change' }],
        documentCode: [{required: true, message: "请输入公文编号", trigger: 'change' }],
        documentType: [{required: true, message: "请选择公文类型", trigger: 'change' }],
        readType: [{required: true, message: "请选择阅示类型", trigger: 'change' }],
      }
    },
  },
  created() {
    this.dict.load('issuingUnit','officialDocumentEmergencyLevel', 'officialDocumentReadType', 'officialDocumentConfidentialityLevel', 'officialDocumentName', 'documentFlowStatus', 'readingStatus');
  },
  mounted() {
    this.form = this.params
    this.showDetail = true
    this.isAdd = false
    this.getDetail()
    
  },
  methods: { 
    remove (id) {
      if(this.form.flowUsers.length<=1){
        return this.$message.error("至少留一个流转对象！");
      }
      this.$confirm('确定删除该传阅人员吗？').then(() => {
        this.instance.post(`/app/appofficialdocumentflow/delete?ids=${id}`).then(res => {
          if (res.code == 0) {
            this.$message.success('删除成功！')
            this.getDetail()
          }
        })
      })
    },
    formatName (name) {
      if(name == undefined){
        return
      }
      return name.substr(name.length - 2, name.length > 2 ? (name.length - 1) : name.length)
    },
    addPeople() {  //指派人员
      this.instance.post(`/app/appofficialdocumentinfo/flowById`,null,{
        params:{
          flowUserId:this.addFlow[0].id,
          flowUserName:this.addFlow[0].name,
          avatar:this.addFlow[0].avatar,
          flag:0,
          id:this.form.id,
        }
      }).then(res => {
        if (res.code == 0) {
          this.$message({
            message:"指派成功",
            type:"success"
          })
          this.getDetail()
          this.addFlow = []
        }
      })
    },
    addFlowChange() { //添加传阅人员
      let data = this.form
      const fileIds = data.files.length ? data.files.map(item => item.id) : []
      const flowUsers = [...this.addFlow].map(item => {
        return {
          flowUserId: item.id,
          flowUserName: item.name,
          avatar: item.avatar
        }
      })
      delete data.files
      this.instance.post(`/app/appofficialdocumentflow/add`, {
        id: this.form.id,
        ...data,
        status: '1',
        flowUsers,
        fileIds
      }).then(res => {
        if (res.code == 0) {
          this.$message.success('添加成功')
          this.getDetail()
          this.addFlow = []
        }
      })
    },
    onChange() {
      if (!this.addUser.length) {
        return this.$message.error('请选择流转人员')
      }

      if (this.form.readType === '0' && this.form.status === '0') {
        // 开始流转
        let data = this.form
        const flowUsers = [...this.addUser].map(item => {
          return {
            flowUserId: item.id,
            flowUserName: item.name,
            avatar: item.avatar
          }
        })
        const fileIds = data.files.length ? data.files.map(item => item.id) : []
        delete data.files
        this.instance.post(`/app/appofficialdocumentinfo/addOrUpdate`, {
          id: this.form.id,
          ...data,
          status: '1',
          flowUsers: flowUsers,
          fileIds
        }).then(res => {
          if (res.code == 0) {
            this.$message.success('流转成功')
            this.getDetail()
          }
        })
      } else {
        // 再次流转
        this.instance.post(`/app/appofficialdocumentinfo/flowById`, null, {
          params: {
            flag: '1',
            flowUserId: this.addUser[0].id,
            flowUserName: this.addUser[0].name,
            avatar: this.addUser[0].avatar,
            id: this.form.id
          }
        }).then(res => {
          if (res.code == 0) {
            this.$message.success('添加成功')
            this.getDetail(this.id)
          }
        })
      }
    },
    readTypeChange() {
      if(this.form.readType == 0) {
        this.isMultiple = false
        if(this.form.flowUsers.length > 1) {
          this.form.flowUsers = []
        }
      }else {
        this.isMultiple = true
      }
    },
    getDetail() {
      this.instance.post(`/app/appofficialdocumentinfo/queryDetailById?id=${this.params.id}&flag=0`, null).then((res) => {
        if (res.code == 0) {
          this.form = {...res.data}
          this.form.files = this.form.files || []
          if (res.data.readType === '1') {
            this.tableData = res.data.flowUsers
            this.total = res.data.flowUsers.length
          }
        }
      });
    },
    save(formName, status){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submit(status)
        } else {
          return false;
        }
      });
    },
    submit(status) {
      this.form.flowUsers.map(item => {
        item.flowUserId = item.id,
        item.flowUserName = item.name
      })

      this.form.fileIds = []
      if(this.form.files.length) {
        this.form.files.map((item) => {
          this.form.fileIds.push(item.id)
        })
      }
      this.instance.post(`/app/appofficialdocumentinfo/addOrUpdate`, {
        ...this.form,
        status: status
      }, null).then((res) => {
        if (res.code == 0) {
          if(!this.isAdd){
            this.$message.success("编辑成功");
          }else{
            this.$message.success("提交成功");
            this.cancel(true)
          }
        }
      });
    },
    addCancel() {
      if(this.params.id) { //新增
        this.cancel(true)
      }else {
        this.showDetail = true
      }
    },
    cancel(isRefresh) {
      this.$emit('change', {
        type: 'list',
        isRefresh: !!isRefresh
      })
    },
    downFileAll () {
      if (this.form.files.length > 0) {
        this.instance.post('/app/appofficialdocumentinfo/downLoadAllFileForDetail', null, {
          responseType: 'blob',
          params: {
            id: this.form.id
          }
        }).then((res) => {
          const link = document.createElement('a')
          let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          var num = ''
          for (let i = 0; i < 10; i++) {
            num += Math.ceil(Math.random() * 10)
          }
          link.setAttribute('download', '公文文件' + '.zip')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        })
      } else {
        this.$message.error('暂无附件提供下载')
      }
    },
    endCirculation () {
      this.$confirm('确定结束流转？').then(() => {
        this.instance.post(`/app/appofficialdocumentinfo/finishById?id=${this.form.id}`).then(res => {
          if (res.code == 0) {
            this.$message.success('操作成功')
            this.cancel(true)
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
  },
};
</script>

<style lang="scss" scoped>
.managementDetail {
  height: 100%;
  overflow: auto;
  background: #f3f6f9;
  .above{
    overflow: hidden;
    width: 100%;
    .left{
      width: 50%;
      float: left;
    }
    .right{
      width: 50%;
      float: right;
    }
    .el-select{
      width: 100%;
    }
    .el-date-editor.el-input{
      width: 100%;
    }
  }
  .iconEdit,.Edit{
    color:#5088FF;
    font-size: 12px;
    cursor: pointer;
    padding-left: 8px;
  }
}
  .ai-steps {
    padding-bottom: 40px;
    .ai-steps__item {
      display: flex;
      position: relative;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 44px;

      &:after {
        position: absolute;
        left: 20px;
        top: 40px;
        width: 1px;
        height: 44px;
        background: #DDDDDD;
        content: ' ';
      }

      &:last-child {
        padding-bottom: 0;

        &:after {
          display: none;
        }
      }

      .ai-steps__item--left {
        display: flex;
        position: relative;

        .ai-steps__item--content {
          span {
            color: #333;
            font-size: 16px;
          }

          h2 {
            margin-top: 4px;
            color: #666666;
            font-size: 14px;
          }

          p {
            margin-top: 8px;
            color: #666666;
            font-size: 14px;
          }
        }

        .ai-steps__item__avatar {
          position: relative;
          width: 40px;
          height: 40px;
          margin-right: 16px;

          i {
            position: absolute;
            bottom: 4px;
            right: 0;
            color: #2ea222;
            font-size: 12px;
          }

          img, h2 {
            width: 40px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            border-radius: 50%;
            color: #fff;
            font-size: 14px;
            background: #2266FF;
          }
        }
      }

      .ai-steps__item--right {
        margin-left: 20px;
        flex-shrink: 0;
        color: #999999;
        font-size: 14px;
      }
    }
  }
</style>