<template>
  <div>
    <el-breadcrumb class="heading">
      <el-breadcrumb-item :to="{ path: '/' }">平台首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/oilsupplier/annualaudit' }">年审申请表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" style="height: calc(100vh - 115px);">
      <div slot="header">
        <span>
          <i class="icon icon-table2"></i> 年审申请表
        </span>
        <span style="float: right;">
          <el-button type="primary" size="mini" style="margin-left:10px; margin-top: -4px;" @click="addaudit">添加
          </el-button>
        </span>
        <el-form ref="form" :inline="true" style="float: right; margin-top: -10px">
          <el-form-item label="年审日期">
            <el-date-picker size="mini" style="width: 220px" v-model="CreateOn" type="daterange" range-separator="至"
              start-placeholder="生成日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="准入类别">
            <el-select size="mini" style="width:100px" v-model="searchForm.SupplierTypeName" placeholder="准入类别">
              <el-option label="物资类" value="01"></el-option>
              <el-option label="技术服务类" value="03"></el-option>
              <el-option label="基建类" value="02"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-dropdown split-button type="primary" size="mini" @click="handleSearch" @command="searchCommand">
              查询
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="search">高级查询</el-dropdown-item>
                <el-dropdown-item command="clear">查询重置</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="entityList" border height="calc(100vh - 243px)" style="width: 100%" @sort-change="orderby">
        <el-table-column label="操作" min-width="180" align="center" fixed>
          <template slot-scope="scope">
            <router-link
              :to="'/oilsupplier/annualaudit/' + scope.row.SupplierId + '/operation?certid=' + scope.row.CerId +'&WorkflowId='+scope.row.WorkflowId+'&Status='+scope.row.Status+'&Step='+scope.row.Step">
              <el-button type="primary" plain title="查看详情" size="mini">打开</el-button>
            </router-link>
            <el-dropdown @command="MoreCmdClick">
              <el-button size="mini" type="primary" plain style="margin-left:5px;">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="GetCommand('History', scope.row)">审批流程</el-dropdown-item>
                <el-dropdown-item :command="GetCommand('Delete', scope.row)" :disabled="scope.row.Status != 0" divided>
                  删除数据</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>

        <el-table-column prop="RecUnitId" label="推荐单位编码" sortable min-width="130" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="AccessCardNo" label="准入证号" sortable min-width="110" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="SupplierTypeName" label="准入类别" sortable min-width="110" align="center"
          show-overflow-tooltip>
          <template slot-scope="scope">
            {{ checkSupplierTypeName(scope.row.SupplierTypeName) }}
          </template>
        </el-table-column>
        <el-table-column prop="SupplierName" label="企业名称" sortable min-width="130" align="center" show-overflow-tooltip>
        </el-table-column>
        <!-- <el-table-column prop="OrganCode" label="组织机构代码" sortable min-width="130" align="center" show-overflow-tooltip>
        </el-table-column> -->
        <el-table-column sortable min-width="110" align="center" prop="Status" label="审核状态">
          <template slot-scope="scope">
            <el-alert v-if="scope.row.Status=='2'" :closable="false" style="background:rgba(255,255,255,0.2)"
              title="初审未通过" type="error">
            </el-alert>
            <el-alert v-if="scope.row.Status=='4'" :closable="false" style="background:rgba(255,255,255,0.2)"
              title="专业审核通过" type="success">
            </el-alert>
            <el-alert v-if="scope.row.Status=='0'" :closable="false" style="background:rgba(255,255,255,0.2)"
              title="已申请" type="info">
            </el-alert>
            <el-alert v-if="scope.row.Status=='1'" :closable="false" style="background:rgba(255,255,255,0.2)"
              title="初审通过" type="success">
            </el-alert>
            <el-alert v-if="scope.row.Status=='5'" :closable="false" style="background:rgba(255,255,255,0.2)"
              title="专业审核未通过" type="error">
            </el-alert>
            <el-alert v-if="scope.row.Status=='3'" :closable="false" style="background:rgba(255,255,255,0.2)"
              title="业务处已接收" type="warning">
            </el-alert>
          </template>
        </el-table-column>
        <el-table-column prop="ApplyTime" sortable min-width="130" label="年审日期" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ jstimehandle(scope.row.ApplyTime+'') }}
          </template>
        </el-table-column>
        <el-table-column prop="CreateOn" sortable min-width="130" label="申请日期" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ jstimehandle(scope.row.CreateOn+'') }}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 15, 20, 25]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
        :total="currentItemCount">
      </el-pagination>
    </el-card>

    <el-dialog title="高级查询" :visible.sync="dialogVisible" width="720px">
      <el-form ref="searchForm" label-width="110px">
        <el-row>

          <el-col :span="12">
            <el-form-item label="推荐单位编码">
              <el-input size="mini" v-model="searchForm.RecUnitId" style="width:100%" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="准入证号">
              <el-input size="mini" v-model="searchForm.AccessCardNo" style="width:100%" placeholder="请输入">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="准入类别">
              <el-input size="mini" v-model="searchForm.SupplierTypeName" style="width:100%" placeholder="请输入">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="企业名称">
              <el-input size="mini" v-model="searchForm.SupplierName" style="width:100%" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleSearch">查 询</el-button>
      </span>
    </el-dialog>
    <el-dialog title="年审申请添加" :visible.sync="addshow" width="360px">
      <el-form label-width="90px" :model="entityForm" :rules="rules" ref="EntityFormref">
        <el-row>
          <el-col :span="24">
            <el-form-item label="企业名称" prop="SupplierId" required>
              <el-select filterable default-first-option ref="supselect" v-model="entityForm.SupplierId" required
                placeholder="请选择" @change="supplierchange" style="width: 100%">
                <el-option v-for="item in selectsupplierlist" :key="item.Id" :label="item.Realname" :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="准入类别" prop="SupplierTypeName" required>
              <el-select filterable default-first-option v-model="entityForm.SupplierTypeName" placeholder="请选择"
                style="width: 100%">
                <el-option label="物资类" value="01"></el-option>
                <el-option label="技术服务类" value="03"></el-option>
                <el-option label="基建类" value="02"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="审批人">
              <el-input ref="selectAuditer" readonly v-model="auditerName" placeholder="请选择审批人">
                <el-button slot="append" icon="el-icon-search" @click="chooseAuditorShow"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="说明">
              <el-input v-model="entityForm.Remark" type="textarea" placeholder="请输入说明内容">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span style="float: right;margin-top:-10px;">
        <el-button size="small" @click="addshow = false">取 消</el-button>
        <el-button type="primary" size="small" @click="addAnnualAudit()">确 定</el-button>
      </span>
      <br>
    </el-dialog>
    <el-dialog title="审核历史查看" :visible.sync="historyVisible" width="900px">
      <wf-history ref="WfHistory" :entryinfo="entrydetail"></wf-history>
    </el-dialog>
    <choose-auditor ref="chooseAuditor" @close="setAuditer" @hideChooseAuditer="chooseAuditorVisible=false"
      :visible="chooseAuditorVisible"></choose-auditor>
  </div>
</template>
<script>
  import {
    mapGetters
  } from 'vuex';
  import WfHistory from '@/components/workflow/wfhistory.vue'
  import supplierapi from '@/api/oilsupplier/supplier'
  import api from '@/api/oilsupplier/annualaudit'
  import ChooseAuditor from '@/components/oilsupplier/chooseauditor'

  export default {
    components: {
      WfHistory,
      ChooseAuditor
    },
    computed: {
      ...mapGetters({
        authUser: 'authUser'
      })
    },
    name: 'annualaudit',

    data() {
      return {
        chooseAuditorVisible: false,
        orgtreelist: [],
        orgtreeprops: {
          value: 'id',
          label: 'Fullname',
          children: 'children'
        },
        historyVisible: false,
        addshow: false,
        dialogVisible: false,
        delevisble: false,
        organizeOption: [], // 审批部门
        auditerOption: [],
        auditer: '',
        auditerName: '',
        //列表数据
        selectsupplierlist: [],
        entityList: [],
        //分页参数
        size: 10,
        currentPage: 1,
        currentItemCount: 0,
        //列表排序
        Column: {
          Order: '',
          Prop: ''
        },
        //工作流
        entrydetail: {
          process: 'oil_audit_apply',
          business: '',
          instance: '',
        },
        //查询时间
        CreateOn: [new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000), new Date()],
        //查询项
        searchFormReset: {},
        entityForm: {
          Id: '',
          SupplierName: '',
          SupplierId: '',
          SupplierTypeName: '',
          FirstAudit: '',
          auditer: '',
          Step: 0,
          Remark: ''
        },
        searchForm: {
          Id: '',
          RecUnitId: '',
          AccessCardNo: '',
          SupplierTypeName: '',
          SupplierName: '',
          Num: '',
          ProjectName: '',
          Performance: '',
          WorkRange: '',
          Status: '',
          BackReason: '',
          ApplyTime: '',
          AuditDate: '',
          EnterUserId: '',
          EnterUserName: '',
          EnterUserTel: '',
          SCR: '',
          SCRQ: '',
          SCYJ: '',
          SCJG: '',
          SPR: '',
          SPRQ: '',
          SPYJ: '',
          SPJG: '',
          CreateOn: '',
          CreateUserId: '',
          CreateBy: '',
          ModifiedOn: '',
          ModifiedUserId: '',
          ModifiedBy: '',
        },
        rules: {
          SupplierId: [{
            required: true,
            message: '请选择企业名称',
            trigger: 'blur'
          }, ],
          SupplierTypeName: [{
            required: true,
            message: '请选择准入类别',
            trigger: 'blur'
          }],
          FirstAudit: [{
            required: true,
            message: '请选择初审单位',
            trigger: 'blur'
          }],
          auditer: [{
            required: true,
            message: '请选择审批人',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      //查询条件初始值备份
      Object.assign(this.searchFormReset, this.searchForm)
      //查询列表
      this.initDatas()
      this.getselectsupplier()
      this.getorgtreelist()
      this.getDictOptions()
    },
    methods: {
      initDatas() {
        //分页及列表条件
        let params = {
          _currentPage: this.currentPage,
          _size: this.size,
          Order: this.Column.Order,
          Prop: this.Column.Prop,
        }
        let myCreateOn = []
        // 解析时间
        if (this.CreateOn.length == 2) {
          this.CreateOn[1].setHours(23)
          this.CreateOn[1].setMinutes(59)
          this.CreateOn[1].setSeconds(59)
          myCreateOn.push(this.formatDateTime(this.CreateOn[0]))
          myCreateOn.push(this.formatDateTime(this.CreateOn[1]))
        }
        //查询条件
        Object.assign(params, this.searchForm)
        //访问接口
        api.getList(myCreateOn.join(','), params, this.$axios).then(res => {
          this.entityList = res.data.items
          console.log("---this.entityList ----", this.entityList)
          this.currentItemCount = res.data.currentItemCount
        }).catch(err => {
          console.error(err)
        })
      },
      getorgtreelist() {
        let _this = this
        let params = {
          IsInnerOrganize: 1
        }
        _this.$axios.get('organizes/orgalllist', {
            params
          })
          .then(res => {
            _this.orgtreelist = window.toolfun_gettreejson(res.data.items, 'Id', 'Parentid', 'Id,Fullname')
            if (_this.authUser.Profile.IsCompanyUser === 0) {
              this.secOrganize = _this.authUser.Profile.Superior.split(',').map((val) => {
                return parseInt(val)
              })
              this.auditOrgChang(this.secOrganize)
            }
          })
          .catch(err => {
            console.error(err)
          })
      },
      setAuditer(val, name) {
        console.log("------", val, name)
        this.auditer = val
        this.auditerName = name
        this.chooseAuditorVisible = false
      },
      chooseAuditorShow() {
        console.log("---this.entityForm---",this.entityForm)
        this.$refs['chooseAuditor'].getorgtreelist(this.entityForm.SupplierTypeName)
        this.chooseAuditorVisible = true
      },
      supplierchange(value) {
        let obj = {};
        obj = this.selectsupplierlist.find((item) => {
          return item.Id === value;
        });
        this.entityForm.SupplierName = obj.Realname
      },
      addAnnualAudit() {
        this.$refs['EntityFormref'].validate((valid) => {
          if (valid) {
            this.entityForm.auditer = this.auditer
            console.log("----this.entityForm.auditer--", this.entityForm.auditer)
            api.addEntity(this.entityForm, this.entityForm.auditer, this.$axios).then(res => {
              if (res.data.code === 0) {
                console.log("--------res.data----", res.data)
                //保存成功后，初始化数据，变成修改
                this.entityForm.Id = res.data.item;
                this.initDatas();
                this.addshow = false
                this.$message({
                  type: 'success',
                  message: res.data.message
                });

              } else {
                this.$message({
                  type: 'warning',
                  message: res.data.message
                });
              }
            }).catch(err => {
              console.error(err)
            });
          }
        })
      },
      addaudit() {
        this.addshow = true
      },

      getselectsupplier() {
        api.getSupList(this.$axios).then(res => {
          if (res.data.items.length != 0) {
            for (var i = 0; i < res.data.items.length; i++) {
              this.selectsupplierlist.push({
                Id: res.data.items[i].Id,
                Realname: res.data.items[i].SupplierName
              })
            }
          }
        }).catch(err => {
          console.error(err)
        })
      },

      getorgtreelist() {
        let _this = this
        let params = {
          IsInnerOrganize: 1
        }
        _this.$axios.get('organizes/orgalllist', {
            params
          })
          .then(res => {
            _this.orgtreelist = window.toolfun_gettreejson(res.data.items, 'Id', 'Parentid', 'Id,Fullname')
          })
          .catch(err => {
            console.error(err)
          })
      },

      getDictOptions() {
        supplierapi.getDictList(this.$axios).then(res => {
          this.dictData = res.data.items
          //this.organizeOption = res.data.items['Organizes']
        }).catch(err => {
          console.error(err)
        })
      },
      checkSupplierTypeName(val) {
        if (val == '01') {
          return '物资类'
        } else if (val == '02') {
          return '基建类'
        } else if (val == '03') {
          return '技术服务类'
        }
      },

      searchCommand(command) {
        if (command == 'search') {
          this.dialogVisible = true
        } else if (command == 'clear') {
          this.clearSearch()
        }
      },
      //列表排序功能
      orderby(column) {
        if (column.order == 'ascending') {
          this.Column.Order = 'asc'
        } else if (column.order == 'descending') {
          this.Column.Order = 'desc'
        }
        this.Column.Prop = column.prop
        this.initDatas()
      },
      clearSearch() {
        Object.assign(this.searchForm, this.searchFormReset);
        //this.searchForm = this.searchFormReset;
        this.CreateOn = ''
        this.initDatas()
      },
      handleSearch() {
        this.currentPage = 1;
        this.dialogVisible = false;
        this.initDatas();
      },
      handleCurrentChange(value) {
        this.currentPage = value
        this.initDatas()
      },
      handleSizeChange(value) {
        this.size = value
        this.currentPage = 1
        this.initDatas()
      },
      deleteEntity(row) {
        api.deleteEntity(row.Id, this.$axios).then(res => {
          if (res.data.code === 0) {
            this.initDatas();
            this.$message({
              type: 'success',
              message: res.data.message
            });

          } else {
            this.$message({
              type: 'warning',
              message: res.data.message
            });
          }
        }).catch(err => {
          console.error(err)
        });
      },

      getvalues(val) {
        this.entrydetail.business = val.Id
        this.entrydetail.instance = val.WorkflowId
        this.historyVisible = true
      },

      MoreCmdClick(cmd) {
        if (cmd.Command == 'History') {
          this.getvalues(cmd.row)

        } else if (cmd.Command == 'Delete') {
          this.deleteEntity(cmd.row)
        }
      },

      GetCommand(cmdType, row) {
        let cmd = {}
        cmd.Command = cmdType
        cmd.row = row
        return cmd
      },

      jstimehandle(val) {
        if (val === '') {
          return '----'
        } else if (val === '0001-01-01T00:00:00Z') {
          return '----'
        } else if (val === '0001-01-01T08:00:00+08:00') {
          return '----'
        } else if (val === '5000-01-01T23:59:59+08:00') {
          return '永久'
        } else {
          val = val.replace('T', ' ')
          return val.substring(0, 10)
        }
      },

      formatDateTime(date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
      }
    }
  }

</script>

<style lang="scss">

</style>
