<template>
  <section class="pointsDeclaration">
    <ai-list isTabs>
      <template slot="content">
        <ai-search-bar bottomBorder>
          <template slot="left">
            <el-button type="primary" icon="iconfont iconAdd" @click="onAdd" v-if="$permissions('app_appvillagerintegraldeclare_edit')">代申报</el-button>
            <el-button icon="iconfont iconEdit" @click="batchAduit()" :disabled="!Boolean(selectionList.length)"v-if="$permissions('app_appvillagerintegraldeclare_edit')">批量审核</el-button>
            <ai-select
              v-model="search.status"
              @change="page.current = 1, getList()"
              placeholder="发布状态"
              :selectList="dict.getDict('integralDeclareStatus')">
            </ai-select>
            <div class="times_div">
              <p class="times">申报时间</p>
              <el-date-picker
                v-model="search.declareTimeStart"
                type="date"
                size="small"
                @change="page.current = 1,getList()"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="开始日期">
              </el-date-picker>
              <el-date-picker
                v-model="search.declareTimeEnd"
                type="date"
                size="small"
                @change="page.current = 1,getList()"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="结束日期">
              </el-date-picker>
            </div>
          </template>
          <template slot="right">
            <el-input
              v-model="search.familyName"
              class="search-input"
              size="mini"
              placeholder="申诉人/申诉对象/..."
              clearable
              @keyup.enter.native="page.current = 1, getList()"
              @clear="page.current = 1, getList()"
              suffix-icon="iconfont iconSearch" />
          </template>
        </ai-search-bar>
        <ai-table
          :tableData="tableData"
          :col-configs="colConfigs"
          :total="page.total"
          :current.sync="page.current"
          :size.sync="page.size"
          @getList="getList"
          @selection-change="handleSelectionChange">
          <el-table-column slot="selection" type="selection" width="55" :selectable="(row, index)=>{
              if(row.status==0){
                return true
              }else{
                return false
              }                  
          }"></el-table-column>
          <el-table-column slot="options" label="操作" align="center">
            <template slot-scope="{ row }">
              <div class="table-options">
                <el-button
                  type="text"
                  :disabled="row.status === '0' || $permissions('app_appvillagerintegraldeclare_edit')"
                  title="编辑"
                  @click="toEdit(row)">
                  编辑
                </el-button>
                <el-button
                  type="text"
                  :disabled="$permissions('app_appvillagerintegraldeclare_detail')"
                  title="详情"
                  @click="toEdit(row)">
                  详情
                </el-button>
              </div>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <ai-dialog
      title="积分代申报"
      :visible.sync="dialog.visibleAdd"
      :customFooter="true"
      :destroyOnClose="true"
      width="720px"
      @close="init('ruleForm')">
      <div class="form_div">
        <el-form
          ref="ruleForm"
          :model="dialogInfo"
          :rules="formRules"
          size="small"
          label-suffix="："
          label-width="140px">
          <el-form-item label="代申报家庭" prop="users">            
            <ai-person-select :customClicker="true" :isMultiple="true" :chooseUserList.sync="dialogInfo.users" :instance="instance" url="/app/appvillagerintegralfamilymember/list" >
              <template name="option" v-slot:option="{ item }">
                <span class="iconfont iconProlife">{{ item.name }}</span>
                <ai-id mode="show" :show-eyes="false" :value="item.idNumber" />
              </template>
            </ai-person-select>
          </el-form-item>
          <el-form-item label="代申报说明" prop="declareDescription">
            <el-input type="textarea" :rows="3" placeholder="请输入…" maxlength="100" show-word-limit v-model="dialogInfo.declareDescription"></el-input>
          </el-form-item>
          <el-form-item label="照片" prop="fileList">
            <div class="upload">
              <ai-uploader :instance="instance" v-model="dialogInfo.fileList" :limit="9" ></ai-uploader>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer" slot="footer">
        <el-button @click="dialog.visibleAdd=false" size="medium">取消</el-button>
        <el-button @click="declare('ruleForm')" type="primary" size="medium">提交</el-button>
      </div>
    </ai-dialog>
    <ai-dialog
      title="申报审核"
      :visible.sync="dialog.visibleDetail"
      :customFooter="true"
      :destroyOnClose="true"
      width="720px"
      @close="init('rules')">
      <div class="form_content" v-if="!isBatch">
        <div class="form_flex form_info">
          <div>
            <span class="form_label">申报人：</span>
            <span class="form_value">{{rowInfo.declareName}}</span>
          </div>
          <div>
            <span class="form_label">申报对象：</span>
            <span class="form_value">{{rowInfo.declareObjName}}</span>
          </div>
          <div>
            <span class="form_label">户主：</span>
            <span class="form_value">{{rowInfo.familyName}}</span>
          </div>
        </div>
        <div class="form_info">
          <span class="form_label">申报说明：</span>
          <span class="form_value">{{rowInfo.declareDescription}}</span>
        </div>
        <div class="form_info">
          <span class="form_label">申报时间：</span>
          <span class="form_value">{{rowInfo.declareTime}}</span>
        </div>
        <div class="form_info">
          <span class="form_label">照片：</span>
          <span class="form_value">
              <ai-uploader  :disabled="true" :instance="instance" v-model="rowInfo.fileList" :limit="9" ></ai-uploader>
          </span>
        </div>
      </div>
      <div class="form_div">
        <el-form
          ref="rules"
          :model="dialogDetail"
          :rules="formRules"
          size="small"
          label-suffix="："
          v-show="rowInfo.status==0"
          label-width="90px"
        >
          <el-form-item label="类型" prop="doType">
            <el-radio-group v-model="dialogDetail.doType" @change="changeDoType">
              <el-radio label="1">加分</el-radio>
              <el-radio label="0">扣分</el-radio>
              <el-radio label="2">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="事项" prop="ruleId" v-if='dialogDetail.doType!=2'>
            <el-select v-model="dialogDetail.ruleId" placeholder="请选择..." @change="ruleChange">
                  <el-option
                      v-for="(item,i) in rulesList"
                      :key="i"
                      :label="item.ruleName"
                      :value="item.id"
                  ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="积分" prop="doIntegral" v-if='dialogDetail.doType!=2'>
            <el-col :span="1.5" style="margin-right: 8px;">{{dialogDetail.doType==0? '减少' :'增加'}}</el-col>
            <el-col :span="6" style="margin-right: 8px;width:120px;"><el-input type="number" v-model="dialogDetail.doIntegral" :placeholder="placeholder" :disabled="integralEdit"></el-input></el-col>
            <el-col :span="1" style="margin-right: 8px;">分</el-col>            
          </el-form-item>
          <el-form-item label="备注说明">
            <el-input type="textarea" :rows="3" maxlength="100" placeholder="请输入…" show-word-limit v-model="dialogDetail.remark"></el-input>
          </el-form-item>
        </el-form>
        <ai-wrapper
            label-width="70px"
            v-if="rowInfo.status!=0"
            :columnsNumber="1">
            <ai-info-item label="类型："><span  :style="{color:colorList[rowInfo.status]}" >{{dict.getLabel('integralDeclareStatus', rowInfo.status)}}</span></ai-info-item>
            <ai-info-item label="事项：" v-if='rowInfo.doType!=2'><span >{{rowInfo.ruleName}}</span></ai-info-item>
            <ai-info-item label="积分：" v-if='rowInfo.doType!=2'>{{rowInfo.doType==0? '减少' :'增加'}}<span style="color:#2266FF">{{Math.abs(rowInfo.doIntegral)}}</span>分</ai-info-item>
            <ai-info-item label="备注说明："><span>{{rowInfo.remark||'-'}}</span></ai-info-item>
        </ai-wrapper>
      </div>
      <div class="dialog-footer" slot="footer" v-if="rowInfo.status==0">
        <el-button @click="dialog.visibleDetail=false" size="medium">取消</el-button>
        <el-button @click="onConfirm('rules')" type="primary" size="medium">提交</el-button>
      </div>
    </ai-dialog>
  </section>
</template>

<script>
import {mapState} from 'vuex';
export default {
  name: "pointsDeclaration",

  props: {
    instance: Function,
    dict: Object,
    bizType:String,
    areaId:String
  },

  data() {
     var integral = (rule, value, callback) => {
      if (value) {
        if (/^[1-9]\d*$/.test(value)) {
          if(!this.integralEdit){
              if(Number(value)>=this.sectionNum.min&&Number(value)<=this.sectionNum.max){
                  callback();
              }else{
                  callback(new Error(`请输入${this.sectionNum.min}至${this.sectionNum.max}之间的正整数积分`));
              }
          }else{
            callback();
          }
          
        } else {
          callback(new Error('请输入正整数'));
        }
      } else {
          callback(new Error('请输入正整数'));
      }
    };
    return {
      search: {
          status:'',
          familyName:'',
          declareTimeStart:null,
          declareTimeEnd:null
      },
      page:{
        current: 1,
        size: 10,
        total:0
      },
      colConfigs: [
        { slot: "selection", label: "" },
        { prop: "declareName", label: "申报人", align: "center" },
        { prop: "declareObjName", label: "申报对象", align: "center",hide:this.bizType==1 },
        {
          prop: "familyName",
          label: "户主",
        },
        {
          prop: "declareDescription",
          label: "申诉说明",
          align: "left",
          width:300
        },
        {
          prop: "declareTime",
          label: "申报时间",
          align: "left",
          width:150
        },
        {
          prop: "declareName",
          label: "操作人",
          align: "center",
        },
        {
          prop: "status",
          label: "状态",
          align: "center",
          render: (h, {row}) => {
              return h('span', {style: {color: this.dict.getColor('integralDeclareStatus', row.status)}}, this.dict.getLabel('integralDeclareStatus', row.status))
          },
        },
        { slot: "options", label: "操作", align: "center" },
      ],
      tableData: [],
      dialog: {
        visibleAdd: false,
        visibleDetail: false,
        title:'积分代申报'
      },
      dialogInfo: {
        users: [],
        reportIds:[],
        declareDescription: "",
        fileList: [],
      },
      dialogDetail: {
        doType: '1',
        ruleId: '',
        doIntegral: '',
        remark: '',
        aduitIds:[],
        ruleName:''
      },
      isBatch:false,
      rulesList:[],
      rowInfo:{},
      formRules: {
        users: [{ required: true, message: "请选择人员", trigger: "change" },],
        declareDescription: [{ required: true, message: "代申报说明", trigger: "blur" }],
        // fileList: [{ required: true, message: "请上传照片", trigger: "blur" },],
        ruleId: [{ required: true, message: "请选择事项", trigger: "blur" }],
        doIntegral: [{ required: true, validator: integral, trigger: "blur" }],
        doType:[{ required: true, message: "请选择类型", trigger: "change" }]
      },
      selectionList:[],
      integralEdit:false,
      sectionNum:{
        min:null,
        max:null
      },
      placeholder:'请输入...'
    };
  },
  computed:{
      colorList(){
          return {
              '0':'#FF8822',
              '1':'#2EA222',
              '2':'#FF4466'
          }
      }
  },
  created() {
    this.dict
      .load([
        'integralDeclareStatus',
        'integralDeclareDoType'
      ]).then(() => {
        this.getList();
      });
  },

  methods: {
    getList() {
      this.instance.post(`/app/appvillagerintegraldeclare/list`, null, {
          params: {
            ...this.search,
            ...this.page,
             bizType:this.bizType,
             areaId:this.areaId
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.tableData = res.data.records;
            this.page.total = res.data.total;
          }
        });
    },
    handleSelectionChange(val){
      this.selectionList=val
      this.dialogDetail.aduitIds=[];
        val.forEach(e=>{
            this.dialogDetail.aduitIds.push(e.id);
        })
    },
    // getSelect(val){
    //     for(let e of val){
    //         this.dialogInfo.reportIds.push(e.id)
    //     }
    // },
    getColor(status){
        return this.dict.getColor('integralDeclareStatus', status)
    },
    onChange(val){

    },
    declare(formName){
        this.dialogInfo.reportIds=[];
        for(let e of this.dialogInfo.users){
            this.dialogInfo.reportIds.push(e.id)
        };
        this.$refs[formName].validate((valid) => {
            if (valid) {
                  this.instance.post("/app/appvillagerintegraldeclare/addOrUpdate", {
                        ...this.dialogInfo,
                         bizType:this.bizType
                    }, null).then(res => {
                        if (res.code==0) {
                            this.dialog.visibleAdd=false;
                            this.getList();
                        }
                    })
            } else {
                return false;
            }
        });
    },
    init(formName){
        this.$refs[formName].clearValidate();
        this.dialogDetail = {
                            doType: '1',
                            ruleId: '',
                            doIntegral: '',
                            remark: '',
                            aduitIds:[],
                            ruleName:''
                          }
          this.dialogInfo=  {
            users: [],
            reportIds:[],
            declareDescription: "",
            fileList: [],
          };
          this.rulesList = [];
    },
    //批量审核
    batchAduit(){
        this.isBatch=true;
        this.rowInfo.status=0;
        this.dialog.visibleDetail = true;
        this.getRules('1')
    },
    getRowDetail(row){
         this.instance.post(`/app/appvillagerintegraldeclare/queryDetailById`, null, {
          params: {
              id:row.id
          },
        }).then((res) => {
          if (res.code == 0) {
              this.rowInfo = {...res.data}
              this.dialog.visibleDetail = true;
              this.dialogDetail.aduitIds=[];
              this.dialogDetail.aduitIds.push(row.id);

          }
        });
    },
    toEdit(row) {
        this.isBatch=false;
        this.getRowDetail(row);
        this.getRules('1')
    },
    changeDoType(val){
        this.dialogDetail.ruleId="";
        this.dialogDetail.ruleName = "";
        this.dialogDetail.doIntegral = "";
        this.placeholder = '请输入...';
        this.$refs.rules.clearValidate();
        this.getRules(val)
    },
    ruleChange(val){
        let item = this.rulesList.find(e => e.id == val);
        this.dialogDetail.doIntegral='';
        this.$refs.rules.clearValidate();
        if(item){
          //固定区间
            this.dialogDetail.ruleName = item.ruleName;
            if(item.integralValueType==0){
                this.dialogDetail.doIntegral = Math.abs(item.integral);
                this.integralEdit = true;
            }else{
                this.integralEdit = false;
                if(Math.abs(item.integralEnd)>Math.abs(item.integralStart)){
                    this.sectionNum.min = Math.abs(item.integralStart);
                    this.sectionNum.max = Math.abs(item.integralEnd);
                }else{
                    this.sectionNum.max = Math.abs(item.integralStart);
                    this.sectionNum.min = Math.abs(item.integralEnd);
                }
                this.placeholder = `${this.sectionNum.min}~${this.sectionNum.max}`
            }
        }
    },
    //事项查询
    getRules(integralType){
        this.instance.post(`/app/appvillagerintegralrule/list`, null, {
          params: {
              integralType,
              size:10000000
          },
        }).then((res) => {
          if (res.code == 0) {
              this.rulesList = res.data.records.filter(e=> e.ruleStatus == 1);
          }
        });
    },
    remove(id) {
      this.$confirm("确定删除该公文及其相关的流转信息？").then(() => {
        this.instance
          .post(`/app/appofficialdocumentinfo/delete?ids=${id}`)
          .then((res) => {
            if (res.code == 0) {
              this.$message.success("删除成功！");
              this.getList();
            }
          });
      });
    },
    onReset() {
      Object.keys(this.search).forEach(e => {
          this.search[e] = "";
      });
      this.search.declareTimeStart = null;
      this.search.declareTimeEnd = null;
      this.getList();
    },

    onAdd() {
      this.dialog.visibleAdd = true;
    },

    onConfirm(formName) {
      this.$refs[formName].validate(v =>{
         if(v){
            this.instance.post("/app/appvillagerintegraldeclare/aduit", {
                        ...this.dialogDetail,
                }, null).then(res => {
                  if (res.code==0) {
                      this.dialog.visibleDetail=false;
                      this.$message.success("提交成功！");
                      this.dialogDetail.aduitIds=[];
                      this.getList();
                  }
            })
         }else{
            return false
         }
      })
    },


  },
};
</script>

<style lang="scss">
.pointsDeclaration {
  height: 100%;
  overflow: auto;
  background: #f3f6f9;
  .times_div{
        .times{
            display: block;
            width: 72px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            background: #F5F5F5;
            border-radius: 2px 0px 0px 2px;
            border: 1px solid #D0D4DC;
            font-size: 14px;
            color:#666666;
        }
    }
  .form_content{
    border-bottom:1px solid #eee;
    .form_flex{
      display: flex;
      div{
        flex: 1;
      }
    }
    .form_info{
      margin-bottom: 8px;
    }
    .form_label{
      display: inline-block;
      color: #999;
      vertical-align: top;
    }
    .form_value{
      display: inline-block;
      color: #333;
      width: calc(100% - 80px);
    }
  }
  .form_div{
    padding-top:24px;
  }
  .status-0 {
    color: #ff8822;
  }

  .status-1 {
    color: #2266ff;
  }

  .status-2 {
    color: #999999;
  }
}
</style>
