<template>
  <div>
    <el-dialog  :title="title" :visible.sync="showDialog" width="1000px" :close-on-click-modal="false"  :before-close="handleClose" append-to-body>
        <el-form :model="form"  ref="form" label-width="80px" label-position="left">
            <template v-if="['5','4','8'].indexOf(form.statutesId) ==-1">
                <el-form-item label="权利要求" prop="claimSort">
                    权要{{ form.claimSort+1 }}
                </el-form-item>
                <el-form-item label="权利内容" prop="claimText">
                    {{ form.claimText}}
                </el-form-item>
            </template>
           
            <el-form-item label="无效理由" prop="statutesContent">
                {{ form.statutesContent }}
            </el-form-item>
            <el-form-item label="证据组合" prop="proofGroupDescription">
                <div v-if="['2','3','4','8'].indexOf(form.statutesId) !=-1">
                    <div v-if="editProofGroupDescription" style="display:flex;align-items:center;">
                        <el-input type="textarea" style="width:100%" v-model="descriptions"></el-input>
                        <el-button type="primary" class="margin-left_10" icon="el-icon-check" circle style="font-size:15px" @click="submitContents()"></el-button>
                        <el-button type="primary" class="margin-left_10" icon="iconfont icon-fanhui" circle style="font-size:15px" @click="cancelContents()"></el-button>
                    </div>
                    <div v-else>
                        {{ form.proofGroupDescription }}
                        <span @click="editContents()" ><el-link type="primary"><i class="iconfont icon-bianji" style="font-size:28px"></i></el-link></span>
                    </div>
                </div>
                <div v-else>
                    {{ form.proofGroupDescription }}
                </div>
                
                
            </el-form-item>
            <div>
                <div  style="display:flex;justify-content:space-between;padding-bottom:10px">
                    <div>无效证据</div>
                    <div v-if="!ifSecondInvalid || showFeature">
                        <el-button type="primary" size="small" @click="featuresHistory" v-if="['4','8'].indexOf(form.statutesId) ==-1">特征拆分历史</el-button>
                        <el-button type="primary" size="small" @click="splitClaim" v-if="['4','8'].indexOf(form.statutesId) ==-1">自动拆分</el-button>
                        <el-button type="primary" size="small" @click="addFeature">添加特征</el-button>
                    </div>
                </div>
                <div style="width:100%">
                   <el-table :data="features" border style="width: 100%" :span-method="objectSpanMethod" :header-cell-style="{'text-align':'center'}">
                        <el-table-column prop="featureOrder" label="特征" width="120" align="center">
                            <template slot-scope="scope">
                                <div>
                                    特征{{scope.row.featureOrder}}
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="featureOrder" label="特征内容" >
                            <template slot-scope="scope">
                                <div v-if="['4','8'].indexOf(form.statutesId) ==-1">
                                   <div v-if="(!ifSecondInvalid || showFeature) && !getFeatureDel(scope.row)">
                                        <el-input type="textarea" :autosize="{maxRows:5}" v-model="scope.row.featureText" @blur="change(scope.row)"></el-input>
                                    </div>
                                    <div v-else>
                                        <span :class="getFeatureDel(scope.row)?'del':''">{{ scope.row.featureText }}</span> 
                                    </div> 
                                </div>
                                <div v-else>
                                    <el-button type="text" size="small" @click="addImage(scope)" v-if="!scope.row.featureText">选择附图</el-button>
                                    <div v-else style="display:flex;align-items:center">
                                        <el-image class="img" :src="$commonJS.checkViewer(scope.row.featureText)" :preview-src-list="[$commonJS.checkViewer(scope.row.featureText)]"></el-image>
                                        <el-button type="text" size="small" @click="delImage(scope.row)"><i class="el-icon-delete" style="font-size:20px"></i></el-button>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="literatureId" label="无效证据" v-if="['2','3','4','8'].indexOf(form.statutesId) !=-1">
                            <template slot-scope="scope" v-if="!getFeatureDel(scope.row)">
                                <div style="display:flex;align-items:center">
                                    <el-select v-model="scope.row.literatureId" multiple placeholder="请选择">
                                        <el-option v-for="item in evidenceList" :key="item.id" :label="`D${item.sysOrder}`" :value="item.id"></el-option>
                                        <el-option label="公知常识" :value="0"></el-option>
                                        <el-option label="惯用手段" :value="-1"></el-option>
                                    </el-select>
                                    <el-button type="text" size="small" @click="delEvidence(scope)"><i class="el-icon-delete" style="font-size:20px"></i></el-button>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="evidenceText" label="无效证据详情" >
                            <template slot-scope="scope" v-if="!getFeatureDel(scope.row)">
                                <div>
                                    <my-RichText v-model="scope.row.evidenceText" placeholder="请输入"></my-RichText>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="evidenceDescription" label="说明">
                            <template slot-scope="scope" v-if="!getFeatureDel(scope.row)">
                                <div>
                                    <el-input type="textarea" :autosize="{maxRows:5}" v-model="scope.row.evidenceDescription" placeholder="请输入"></el-input>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" prop="featureOrder" width="150" align="center">
                            <template slot-scope="scope">
                                <div v-if="!getFeatureDel(scope.row)">
                                    <el-button type="text" size="small" @click="addEvidence(scope.row)">添加无效证据</el-button>
                                    <el-button type="text" size="small" @click="chooseHistory(scope.row)">选择历史无效证据</el-button>
                                    <el-button type="text" size="small" @click="dele(scope)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                   </el-table>
                </div>
            </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" :loading="btnLoading" @click="submit" >确 定</el-button>
        </span>
    </el-dialog>

    <invalid-History ref="invalidHistory" @invalidHistory="getInvalidHistory"></invalid-History>
    <features-History ref="featuresHistory"  @feature="getFeature"></features-History>
    <pictureManageDialog ref="pictureManageDialog" :projectId="projectId" @check="getPicture"></pictureManageDialog>
  </div>
</template>

<script>
import invalidHistory from './invalidHistory.vue';
import featuresHistory from './featuresHistory.vue';
import pictureManageDialog from '../pictureManage/pictureManageDialog.vue';
export default {
  components: {
    invalidHistory,
    featuresHistory,
    pictureManageDialog
  },
  props: {
    projectId:{
        default:0
    },
    ifSecondInvalid:{
        default:false
    }
  },
  data() {
    return {
        showDialog:false,
        btnLoading:false,
        form:{},
        title:'添加无效证据',
        features:[],
        evidenceList:[],
        // 计算表格合并行的数量
        mergeObj: {},
        // 表格合并行的栏位
        mergeArr: ['featureOrder',],
        row:{},
        descriptions:'',
        editProofGroupDescription:false,
        addFeatures:[],
        showFeature:false
    };
  },
  watch: {},
  computed: {
    provisions(){
        return this.$store.state.dictMessage.dictMessage.STATUTE || []
    }
  },
  created() {},
  mounted() {
    this.getEvidenceList()
  },
  methods: {
    //选择附图
    addImage(scope){
        var index = scope.$index
        var data = {
            index : index
        }
        this.$refs.pictureManageDialog.open(data)
    },
    //删除图片
    delImage(row){
        this.$set(row,'featureText','')
        
    },
    //获取选择的图片
    getPicture(val){
        var index = val.index
        var data = val.check
        var order = this.features[index].featureOrder
        var tableData = []
        data.forEach(item=>{
            tableData.push(
                {
                    featureText:item,
                    featureOrder:order
                }
            )
            order = Number(order) + 1
        })
        this.features.splice(index,1,...tableData)
        var feature = JSON.parse(JSON.stringify( this.features))
        this.features = feature
        this.getSpanArr(this.features)
    },
    //是否有删除特征
    getFeatureDel(row){
        if(!row.featureHistories){
            return false
        }
        return row.featureHistories.find(item=>{
            return item.operateMode == 1
        })
    },
    //编辑证据组合描述
    editContents(){
        this.$set(this,'editProofGroupDescription',true)
        this.$set(this,'descriptions',this.form.proofGroupDescription)
    },
    //取消编辑证据组合描述
    cancelContents(){
        this.$set(this,'editProofGroupDescription',false)
    },
    //提交证据组合描述
    submitContents(){
        var params = {
            projectId:this.projectId,
            statutesId:this.form.statutesId,
            claimId:this.form.claimId,
            descriptions:[this.descriptions],
            id:this.form.groupId,
        }
        this.$api.addProofGroup(params).then(response=>{
            if(response.code == 200){
                this.cancelContents()
                this.form.groupId = response.data.data[0]
                this.$emit('save',true)
                this.$set(this.form,'proofGroupDescription',this.descriptions)
            }
        }).catch(error=>{
        })
    },

   getEvidenceList(){
        var params ={
            projectId:this.projectId
        }
        this.$api.queryCompareLiterature(params).then(response=>{
            if(response.code == 200){
                this.evidenceList = response.data.data.sort((a,b)=>{
                    return a.sysOrder - b.sysOrder
                })
            }
        }).catch(error=>{
            this.evidenceList = []
        })
   },
    //打开弹窗
    open(form,feature){
        this.form = form
        this.features = []
        this.addFeatures = []
        if(this.ifSecondInvalid){
            this.features = feature
        }else{
            if(feature && feature.length>0){
                for(var i = 0; i<feature.length;i++){
                    var obj = feature[i].featureHistories.find(item=>{return item.featureGen == 0})
                    if(obj){
                        this.features.push(feature[i])
                    }else{
                        this.addFeatures.push(feature[i])
                    }
                }
            }
        }
        if(this.features.length==0){
            this.showFeature = true
        }
        if(this.form.showFeature){
            this.showFeature = true
        }
        this.getSpanArr(this.features)
        this.showDialog = true
    },
    //关闭弹窗
    handleClose(){
        this.showDialog = false
    },
    //提交
    submit(){
        this.$refs.form.validate((valid) => {
          if (valid) {
            if(!this.form.groupId){
                this.$message.warning('请先添加证据组合！')
                return
            }
            var data = []
            if(this.addFeatures.length>0){
                var order = 0
                if(this.features && this.features.length>0){
                   order = Number(this.features[this.features.length-1].featureOrder) 
                }
                var order2 = Number(this.addFeatures[0].featureOrder)
                if(order + 1 != order2){
                    for(var i = 0;i<this.addFeatures.length;i++){
                        order += 1
                        this.addFeatures[i].featureOrder = order
                    }
                }
                data = this.features.concat(this.addFeatures)
            }else{
                data = this.features
            }
            this.btnLoading = true
            var params = {
                groupId:this.form.groupId,
                evidenceReasonList:data,
                gen:this.ifSecondInvalid?'1':'0'
            }
            this.$api.addEvidenceReason(params).then(response=>{
                if(response.code == 200){
                    this.$message.success('添加成功')
                    this.$emit('save',true)
                    this.btnLoading = false
                    this.handleClose()
                }
            }).catch(error=>{
                this.$message.error('添加失败')
                this.btnLoading = false
            })
          }
        })
    },
    //修改特征
    change(row){
        row.featureId = null
    },
    dele(scope){
        var index = scope.$index
        var row = scope.row
        var num = this.features.filter(item=>{
            return item.featureOrder == row.featureOrder
        }).length
        this.features.splice(index,num)
        for(var i = index;i<this.features.length;i++){
            var order = this.features[i].featureOrder
            this.features[i].featureOrder = Number(order) - 1
            this.features[i].featureId = null

        }
        var feature = JSON.parse(JSON.stringify( this.features))
        this.features = feature
        this.getSpanArr(this.features)
    },
    //删除某个特征的证据
    delEvidence(scope){
        var index = scope.$index
        var row = scope.row
        var num = this.features.filter(item=>{
            return item.featureOrder == row.featureOrder
        }).length
        if(num == 1){
            this.$set(row,'literatureId',[])
        }else{
            this.features.splice(index,1)
            var feature = JSON.parse(JSON.stringify( this.features))
            this.features = feature
            this.getSpanArr(this.features)
        }

    },
    //自动拆分特征
    splitClaim(){
        var claim = this.form.claimText
        var arr = claim.match(/\S*?([，|,|；|;|。])/g)
        var data = []
        var str = ''
        arr.forEach((item,index)=>{
            str += item
            var obj = {
                featureOrder:index+1,
                featureText:item,
                literatureId:[]
            }
            data.push(obj)
        })
        var str2 = claim.replace(str,'')
        if(str2){
            var index = 0
            if(data.length>0){
                index = data[data.length-1].featureOrder   
            }
            var obj = {
                featureOrder:index+1,
                featureText:str2,
                literatureId:[]
            }
            data.push(obj)
        }
        this.features = data
        this.getSpanArr(this.features)
    },
    //添加特征
    addFeature(){
        var order = 0
        if(this.features.length>0){
            order = this.features[this.features.length - 1].featureOrder
        }
        var obj = {
            featureOrder:Number(order) + 1,
            literatureId:[]
        }
        this.features.push(obj)
        this.getSpanArr(this.features)
    },
    //特征拆分历史
    featuresHistory(){
        this.$refs.featuresHistory.open(this.form.claimId)
    },
    //获取特征历史的值
    getFeature(val){
        this.features = val
        this.getSpanArr(this.features)
    },
    //选择历史无效记录
    chooseHistory(row){
        this.row = row
        if(row.featureId){
            this.$refs.invalidHistory.open(row.featureId)
        }else{
            this.$message.warning('该特征无历史无效记录')
        }
    },
    //获取历史无效记录的值
    getInvalidHistory(data){
        if(data.length == 0){
            return false
        }
        var index = this.features.findLastIndex(item=>{
            return item.featureOrder == this.row.featureOrder
        })
        var obj = {
            featureId: this.row.featureId,
            featureOrder : this.row.featureOrder,
            featureText : this.row.featureText,
        }
        var features = []
        for(var i = 0;i<data.length;i++){
            var obj2 = {
                ...obj,
                ...data[i],
                literatureId:data[i].literatures.map(item=>item.id)
            }
            features.push(obj2)
        }
        if(this.features[index].literatureId && this.features[index].literatureId.length>0){
            this.features.splice(index+1,0,...features)
        }else{
            this.features.splice(index,1,...features)
        }
        
        var feature = JSON.parse(JSON.stringify( this.features))
        this.features = feature
        this.getSpanArr(this.features)
    },
    //添加无效证据
    addEvidence(row){
        var index = this.features.findLastIndex(item=>{
            return item.featureOrder == row.featureOrder
        })
        var obj = {
            featureId: row.featureId,
            featureOrder : row.featureOrder,
            featureText : row.featureText,
            literatureId:[]
        }
        this.features.splice(index+1,0,obj)
        var feature = JSON.parse(JSON.stringify( this.features))
        this.features = feature
        this.getSpanArr(this.features)
    },
      //获取每个元素所需合并的行数
    getSpanArr(data) {
        this.scopeRow = []
        this.mergeArr.forEach((key, index1) => {
        let count = 0;
        this.mergeObj[key] = [];
        data.forEach((item, index) => {
            if (index === 0) {
            this.mergeObj[key].push(1);
            } else {
            if (item[key] === data[index - 1][key]) {
                this.mergeObj[key][count] += 1;
                this.mergeObj[key].push(0);
            } else {
                count = index;
                this.mergeObj[key].push(1);
            }
            }
        })
        })
    },
        // 表格合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (!row) {
        return false
        }

        if (this.mergeArr.indexOf(column.property) !== -1) {

        if (this.mergeObj[column.property][rowIndex]) {
            return [this.mergeObj[column.property][rowIndex], 1]
        } else {
            return [0, 0];
        }

        }
    },
  },
};
</script>
<style lang="scss" scoped>
</style>