<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">

          <a-col :md="6" :sm="8">
            <a-form-item label="标题">
              <a-input placeholder="请输入搜索关键词" v-model="queryParam.title"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="状态">
              <a-select v-model="queryParam.status" placeholder="请选择" :allowClear="true" >
                <a-select-option value="0">草稿</a-select-option>
                <a-select-option value="1">处理中</a-select-option>
                <a-select-option value="2">已结束</a-select-option>
                <a-select-option value="3">已撤回</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="结果">
              <a-select v-model="queryParam.result" placeholder="请选择" :allowClear="true" >
                <a-select-option value="0">未提交</a-select-option>
                <a-select-option value="1">处理中</a-select-option>
                <a-select-option value="2">通过</a-select-option>
                <a-select-option value="3">驳回</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="10">
            <a-form-item label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-range-picker
                style="width: 210px"
                v-model="queryParam.createTimeRange"
                format="YYYY-MM-DD"
                :placeholder="['开始时间', '结束时间']"
                @change="onDateChange"
                @ok="onDateOk"
              />
            </a-form-item>
          </a-col>
          <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="6" :sm="24" >
                <a-button type="primary"  style="left: 10px" @click="searchQuery" icon="search">查询</a-button>
                <a-button type="primary"  @click="searchReset" icon="reload" style="margin-left: 8px;left: 10px">重置</a-button>
            </a-col>
          </span>

        </a-row>
      </a-form>
    </div>

    <!-- table区域-begin -->
    <a-table
      bordered
      ref="table"
      size="middle"
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      :scroll="{x: false, y: 470 }"
      @change="handleTableChange">
      <span slot="result" slot-scope="text, r">
        <span v-if="r.result == 0" style="color: #afa8a8">未提交</span>
        <span v-else-if="r.result==1" style="color: orange">处理中</span>
        <span v-else-if="r.result==2" style="color: green">已通过</span>
        <span v-else-if="r.result==3" style="color: red">已驳回</span>
      </span>
      <span slot="status" slot-scope="text, r">
        <span v-if="r.status == 0" style="color: #b8b5b5">草稿</span>
        <span v-else-if="r.result==1" style="color: orange">处理中</span>
        <span v-else-if="r.status==2" style="color: blue">已结束</span>
        <span v-else-if="r.status==3" style="color: magenta">已撤回</span>
      </span>
      <span slot="action" slot-scope="text, r">
          <template v-if="r.status == 0">
            <a href="javascript:void(0);" style="color: #00A0E9" @click="apply(r)" >提交申请</a>
            <a-divider type="vertical" />
            <a href="javascript:void(0);" @click="edit(r)" style="color: #000000">编辑提交数据</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗?" @confirm="() => remove(r)">
              <a href="javascript:void(0);"  style="color: red">删除</a>
            </a-popconfirm>

          </template>
          <template v-else-if="r.status == 1">

            <a href="javascript:void(0);" v-if="r.procInstStatus == 1" @click="handelSubmitCancel(r)"  style="color:#8000ff;">撤回</a>
            <a-divider type="vertical" v-if="r.procInstStatus == 1"/>
            <a href="javascript:void(0);" @click="history(r)" style="color:blue;">查看进度</a>
            <a-divider type="vertical" />
            <a href="javascript:void(0);" @click="detail(r)" style="color:#999;">表单数据</a>
          </template>
          <template v-else-if="(r.status == 2 && r.result == 3) || r.status == 3">
            <a-popconfirm title="确定提交申请吗?" @confirm="() => apply(r)">
              <a href="javascript:void(0);" style="color:#00A0E9;">重新申请</a>
            </a-popconfirm>
            <a-divider type="vertical" />
            <a href="javascript:void(0);" @click="edit(r)" style="color:#000000;">编辑</a>
            <a-divider type="vertical" />
            <a href="javascript:void(0);" @click="history(r)" style="color:blue;">审批历史</a>
          </template>
          <template v-else>
            <a href="javascript:void(0);" @click="detail(r)" style="color:#999;">表单数据</a>
            <a-divider type="vertical" />
            <a href="javascript:void(0);" @click="history(r)" style="color:blue;">审批历史</a>
          </template>
      </span>
      <!-- 字符串超长截取省略号显示-->
      <span slot="logContent" slot-scope="text, record">
          <j-ellipsis :value="text" :length="40"/>
        </span>
    </a-table>
    <!-- table区域-end -->
    <!--流程申请选择-->
    <a-drawer
      title="选择流程" width="33%"
      placement="right"
      :closable="false"
      @close="processModalVisible = false"
      :visible="processModalVisible"
    >
      <a-empty description="无流程可供选择" v-if="activeKeyAll.length==0" />
      <div v-else>
        <a-input-search style="margin-bottom: 10px;width: 200px"
                        placeholder="输入流程名称" @search="onSearchProcess" />
        <a-collapse v-model="activeKey">
          <a-collapse-panel v-for="(value, index)  in activeKeyAll" :header="filterDictText(dictOptions,value)||'未分类'" :key="value">
            <a-list :grid="{ gutter: 10,column:1}" :dataSource="processDataMap[value]">
              <a-list-item slot="renderItem" slot-scope="item">
                <a-card>
                  <div slot="title">
                    <a-row>
                      <a-col span="12" :title="item.name">{{item.name}} </a-col>
                      <a-col span="12" style="text-align: right;">
                        <a href="javascript:void (0)" @click="chooseProcess(item)">发起申请</a>
                      </a-col>
                    </a-row>
                  </div>
                  <b>版本：</b>v.{{item.version}}
                  <br/>
                  <b>说明：</b>{{item.description}}
                </a-card>
              </a-list-item>
            </a-list>
          </a-collapse-panel>
        </a-collapse>
      </div>
    </a-drawer>
    <!--流程表单-->
    <a-modal :title="lcModa.title" v-model="lcModa.visible" :footer="null" :maskClosable="false" width="80%">
      <component :disabled="lcModa.disabled" v-if="lcModa.visible" :is="lcModa.formComponent" :hieg ="lcModa.hieg"
                 :processData="lcModa.processData" :isNew = "lcModa.isNew" :procInstId="lcModa.procInstId" :pictureId="lcModa.pictureId"
                 @afterSubmit="afterSub" @loadData="reloadData" @close="lcModa.visible=false,lcModa.disabled = false"></component>
<!--       -->
    </a-modal>
    <!--提交申请表单-->
    <a-modal title="提交申请" v-model="modalVisible" :mask-closable="false" :width="500" :footer="null">
      <div v-if="modalVisible">
        <!--     <a-form-item label="选择审批人" v-show="showAssign">
               <a-select style="width: 100%"
                 v-model="form.assignees"
                 placeholder="请选择"
                 mode="multiple"
                 :allowClear="true"
               >
                 <a-select-option v-for="(item, i) in assigneeList" :key="i" :value="item.username">{{item.realname}}</a-select-option>
               </a-select>
             </a-form-item>
             <a-form-item label="下一审批人" v-show="isGateway">
               <a-alert  type="info" showIcon message="分支网关处不支持自定义选择下一审批人，将自动下发给所有可审批人。">，将发送给下一节点所有人</a-alert>
             </a-form-item>-->
        <a-form-item label="优先级" prop="priority">
          <a-select v-model="form.priority" placeholder="请选择" :allowClear="true" style="width: 100%">
            <a-select-option :value="0">普通</a-select-option>
            <a-select-option :value="1">重要</a-select-option>
            <a-select-option :value="2">紧急</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="消息通知" v-show="false">
          <a-checkbox v-model="form.sendMessage">站内消息通知</a-checkbox>
          <!--  <a-checkbox v-model="form.sendSms" disabled>短信通知</a-checkbox>
            <a-checkbox v-model="form.sendEmail" disabled>邮件通知</a-checkbox>-->
        </a-form-item>
        <div slot="footer">
          <a-button type="text" @click="modalVisible=false">取消</a-button>
          <div style="display:inline-block;width: 20px;"></div>
          <a-button type="primary" :disabled="submitLoading" @click="applySubmit">提交</a-button>
        </div>
      </div>
    </a-modal>
    <a-modal title="审批历史" v-model="modalLsVisible" :mask-closable="false" :width="'80%'" :footer="null">
      <div v-if="modalLsVisible">
        <historicDetail :procInstId="procInstId"></historicDetail>
      </div>
    </a-modal>
    <a-modal title="确认撤回" v-model="modalCancelVisible" :mask-closable="false" :width="500">
      <a-form ref="delForm" v-model="cancelForm" :label-width="70" v-if="modalCancelVisible">
        <a-form-item label="撤回原因" prop="reason" v-show="false">
          <a-input type="textarea" v-model="cancelForm.reason" :rows="4" />
        </a-form-item>
      </a-form>
      <div slot="footer">
        <a-button type="text" @click="modalCancelVisible=false">取消</a-button>
        <a-button type="primary" :disabled="submitLoading" @click="handelSubmitCancel">提交</a-button>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { activitiMixin } from '@/views/activiti/mixins/activitiMixin'
  import { filterObj } from '@/utils/util';
  import JEllipsis from '@/components/jeecg/JEllipsis'
  import { deleteAction, getAction,downFile } from '@/api/manage'
  import pick from "lodash.pick";
  import JTreeSelect from '@/components/jeecg/JTreeSelect'
  import {initDictOptions, filterDictText} from '@/components/dict/JDictSelectUtil'
  import historicDetail from '@/views/activiti/historicDetail'
  export default {
    name: "applyList",
    mixins:[activitiMixin,JeecgListMixin],
    components: {
      JEllipsis
      ,JTreeSelect
      ,historicDetail
    },
    data () {
      return {
        description: '我的申请',
        // 查询条件
        queryParam: {
          ipInfo:'',
          createTimeRange:[],
          logType:'1',
          keyWord:'',
        },
        tabKey: "1",
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '标题',
            align:"left",
            dataIndex: 'title',
            scopedSlots: { customRender: 'logContent' },
            sorter: true
          },
          {
            title: '所属流程',
            dataIndex: 'processName',
            align:"center",
            sorter: true
          },
          {
            title: '当前环节',
            dataIndex: 'currTaskName',
            align:"center",
            sorter: true
          },
          {
            title: '状态',
            dataIndex: 'status_dictText',
            align:"center",
            scopedSlots: {customRender: 'status'},
            sorter: true

          },
          {
            title: '结果',
            dataIndex: 'result_dictText',
            scopedSlots: {customRender: 'result'},
            align:"center",
            sorter: true
          },

          {
            title: '创建时间',
            dataIndex: 'createTime',
            align:"center",
            sorter: true
          },
          {
            title: '提交申请时间',
            dataIndex: 'applyTime',
            /*customRender:function (text) {
              if(text==1){
                return "登录日志";
              }else if(text==2){
                return "操作日志";
              }else{
                return text;
              }
            },*/
            align:"center",
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: {customRender: 'action'},
          }
        ],
        operateColumn:
          {
            title: '操作类型',
            dataIndex: 'operateType_dictText',
            align:"center",
          },
        labelCol: {
          xs: { span: 1 },
          sm: { span: 2 },
        },
        wrapperCol: {
          xs: { span: 10 },
          sm: { span: 16 },
        },
        url: {
          list: "/actBusiness/listData",
          getProcessDataList: "/activiti_process/listData",
          delByIds:'/actBusiness/delByIds',
          getFirstNode:'/actProcessIns/getFirstNode',
          applyBusiness:'/actBusiness/apply',
          cancelApply:'/actBusiness/cancel',
        },
        processModalVisible: null,
        activeKeyAll: [],
        activeKey: [],
        processDataMap: {},
        searchProcessKey: null,
        addApplyLoading: false,
        lcModa: {
          title:'',
          disabled:false,
          visible:false,
          formComponent : null,
          isNew : false,
          hieg: false,
          procInstId:'',
          pictureId:'',
        },
        form:{
          priority:0,
          assignees:[],
          sendMessage:true
        },
        modalVisible: false,
        showAssign: false,
        assigneeList: [],
        isGateway: false,
        dictPriority: [],
        submitLoading: false,
        error: "",
        /*审批历史*/
        modalLsVisible: false,
        procInstId: '',
        modalCancelVisible: false,
        cancelForm: {}
      }
    },
    methods: {
      initDictConfig() {
        //初始化字典 - 流程分类
        initDictOptions('bpm_process_type').then((res) => {
          if (res.success) {
            this.dictOptions = res.result;
          }
        });
      },
      getQueryParams(){
        var param = Object.assign({}, this.queryParam,this.isorter);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        delete param.createTimeRange; // 时间参数不传递后台
        if (this.superQueryParams) {
          param['superQueryParams'] = encodeURI(this.superQueryParams)
          param['superQueryMatchType'] = this.superQueryMatchType
        }
        return filterObj(param);
      },

      // 重置
      searchReset(){
        var that = this;
        var logType = that.queryParam.logType;
        that.queryParam = {}; //清空查询区域参数
        that.queryParam.logType = logType;
        that.loadData(this.ipagination.current);
      },
      // 日志类型
      callback(key){

        // 动态添加操作类型列
        if (key == 2) {
          this.tabKey = '2';
          this.columns.splice(7, 0, this.operateColumn);
        }else if(this.columns.length == 9)
        {
          this.tabKey = '1';
          this.columns.splice(7,1);
        }

        let that=this;
        that.queryParam.logType=key;
        that.loadData();
      },
      onDateChange: function (value, dateString) {
        console.log(dateString[0],dateString[1]);
        this.queryParam.createTime_begin=dateString[0];
        this.queryParam.createTime_end=dateString[1];
      },
      onDateOk(value) {
        console.log(value);
      },
      apply(v) {
        if (!v.procDefId || v.procDefId == "null") {
          this.$message.error("流程定义为空");
          return;
        }
        this.form.id = v.id;
        this.form.procDefId = v.procDefId;
        this.form.title = v.title;
        // 加载审批人
        this.getAction(this.url.getFirstNode,{procDefId:v.procDefId,tableId:v.tableId,tableName:v.tableName}).then(res => {
          if (res.success) {
            if (res.result.type == 3 || res.result.type == 4) {
              this.isGateway = true;
              this.modalVisible = true;
              this.form.firstGateway = true;
              this.showAssign = false;
              this.error = "";
              return;
            }
            this.form.firstGateway = false;
            this.isGateway = false;
            if (res.result.users && res.result.users.length > 0) {
              this.error = "";
              this.assigneeList = res.result.users;
              // 默认勾选
              let ids = [];
              res.result.users.forEach(e => {
                ids.push(e.username);
              });
              this.form.assignees = ids;
              this.showAssign = true;
            } else {
              this.form.assignees = [];
              this.showAssign = true;
              this.error = '审批节点未分配候选审批人员，请联系管理员！';
            }
            if (this.error){
              this.$message.error(this.error)
              return;
            }
            this.modalVisible = true;
          }else {
            this.$message.error(res.message)
          }
        });

      },
      applySubmit() {
        if (this.showAssign && this.form.assignees.length < 1) {
          this.error = "请至少选择一个审批人";
          this.$message.error(this.error)
          return;
        } else {
          this.error = "";
        }
        this.submitLoading = true;
        var params = Object.assign({},this.form);
        params.assignees = params.assignees.join(",")
        this.postFormAction(this.url.applyBusiness,params).then(res => {
          if (res.success) {
            this.$message.success("操作成功");
            this.loadData();
            this.modalVisible = false;
          }else {
            this.$message.error(res.message)
          }
        }).finally(()=>this.submitLoading = false);
      },
      edit(r,isView) {
        if (!r.routeName) {
          this.$message.warning(
            "该流程信息未配置表单，请联系开发人员！"
          );
          return;
        }
        console.log("isView>>>>>>>>>>>>",isView)
        isView = isView||false;
        this.lcModa.disabled = isView;
        this.lcModa.hieg = isView;
        this.lcModa.title = '修改流程业务信息：'+r.title;
        if (isView) this.lcModa.title = '查看流程业务信息：'+r.title;
        this.lcModa.formComponent = this.getFormComponent(r.routeName).component;
        this.lcModa.processData = r;
        this.lcModa.pictureId=r.procDefId
        if(!r.procInstId){
          r.procInstId='';
        }
        this.lcModa.procInstId=r.procInstId;
        this.lcModa.isNew = false;
        this.lcModa.visible = true;
      },
      remove(r) {
        this.postFormAction(this.url.delByIds,{ids:r.id}).then((res)=>{
          if (res.success){
            this.$message.success(res.message)
            this.loadData();
          }else {
            this.$message.error(res.message)
          }
        })
      },
      cancel(v) {
        this.cancelForm.id = v.id;
        this.cancelForm.procInstId = v.procInstId;
        this.modalCancelVisible = true;
      },
      handelSubmitCancel(v) {
        this.$confirm({
          title: '撤回',
          content: `您确定要撤回吗？`,
          centered: true,
          onOk: () => {
            this.cancelForm.id = v.id;
            this.cancelForm.procInstId = v.procInstId;
            this.submitLoading = true;
            this.postFormAction(this.url.cancelApply,this.cancelForm).then(res => {
              if (res.success) {
                this.$message.success("操作成功");
                this.loadData();
                this.modalCancelVisible = false;
              }else {
                this.$message.error(res.message);
              }
            }).finally(()=>this.submitLoading = false);
          }
        })

      },
      history(v) {
        if (!v.procInstId) {
          this.$message.error("流程实例ID不存在");
          return;
        }
        this.procInstId = v.procInstId;
        this.modalLsVisible = true;
      },
      detail(v) {
        this.edit(v,true);
      },
      chooseProcess(v) {
        if (!v.routeName) {
          this.$message.warning(
            "该流程信息未配置表单，请联系开发人员！"
          );
          return;
        }
        this.lcModa.formComponent = this.getFormComponent(v.routeName).component;
        this.lcModa.title = '发起流程：'+v.name;
        this.lcModa.isNew = true;
        this.lcModa.processData = v;
        this.lcModa.visible = true;
        console.log("发起",v)
      },
      afterSub(formData){
        this.lcModa.visible = false;
        this.$message.success("操作成功！请前往我的申请列表提交审批！")
      },
      reloadData(){
        this.loadData();
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>