<template>
  <div class="container">
    <div style="padding: 0px 20px">
      <div ref="lxHeader">
        <LxHeader icon="md-apps" text="通用巡查" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
          <div slot="content"></div>
          <slot>
            <div>
              <Input style="width: 200px; margin-right: 10px" v-model="searchFields.KeyWord" placeholder="关键字搜索" />
              <Button type="primary" @click="load" style="margin-left: 10px">查询</Button>
            </div>
          </slot>
        </LxHeader>
      </div>
      <div ref="lxTable">
        <el-table :data="tableData" class="v-table" :height="tableHeight" style="width: 100%">
          <el-table-column type="index" width="50" fixed label="序号" align="center"> </el-table-column>
          <el-table-column :prop="column.field" :align="column.align" v-for="(column,index) in columns"
            :label="column.title" :width="column.width" :fixed="column.fixed">
              <template slot-scope="scope">
                <div v-if="column.type=='opt'">
                  <Button ghost size="small" @click="edit(scope.row)" type="primary"
                    style="margin-left: 10px;" v-if="scope.row['status']==3">查看</Button>

                  <Button v-if="scope.row['status']==1" ghost size="small" @click="show(scope.row)" type="primary"
                    style="margin-left: 10px;">编辑</Button>
                  <Button v-if="scope.row['status']==1" ghost size="small" @click="edit(scope.row)" type="primary"
                    style="margin-left: 10px;">审核</Button>
                  <Button v-if="scope.row['status']==2" ghost size="small" @click="edit(scope.row)" type="primary"
                    style="margin-left: 10px;">办结</Button>
                  <Button ghost size="small" @click="del(scope.row)" type="error" style="margin-left: 10px;">删除</Button>
                </div>
                <div v-else-if="column.type=='status'">
                  <el-tag v-if="scope.row[column.field]==1">已提交</el-tag>
                  <el-tag type="success" v-if="scope.row[column.field]==2">已审核</el-tag>
                  <el-tag type="warning" v-if="scope.row[column.field]==3">已办结</el-tag>
                </div>
                <div v-else-if="column.type=='feedback_department_id'">
                    <div v-for="item in selects.departments">
                      <div v-if="scope.row[column.field] == item.id">
                        {{item.name}}
                      </div>

                    </div>
                </div>
                <div v-else-if="column.type=='ask_type_id'">
                  {{scope.row[column.field]}}
                </div>
                <div v-else-if="column.type=='format'">
                  {{scope.row[column.field]?scope.row[column.field].name:""}}
                </div>
                <div v-else>{{scope.row[column.field]}}</div>
              </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination @current-change="handleCurrentChange" :current-page="paginations.page"
            :page-size="paginations.page_size" background layout="prev, pager, next" :total="paginations.total">
          </el-pagination>
        </div>
      </div>


      <el-dialog title="通用巡查编辑" :visible.sync="showdialogFormVisible" width="60%">
        <div class="dialogConcent" :style="{height:clientHeight+'px'}">
          <el-scrollbar style="flex: 1">
            <el-form :model="form" :rules="rules" ref="form" label-position="right" :label-width="formLabelWidth">
              <el-row>
                <el-col :span="10">
                  <el-form-item label="类型" prop="ask_type_id">
                    <el-select @change="showAskContentChange" class="width100" v-model="form.ask_type_id" placeholder="请选择类型">
                      <el-option v-for="item in selects.ask_types" :key="item.id" :label="item.value"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10" :offset="4">
                 <el-form-item label="内容" prop="ask_content_id">
                    <el-select class="width100" v-model="form.ask_content_id" placeholder="请选择内容">
                      <el-option v-for="item in selects.ask_content" :key="item.id" :label="item.value"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="地址" prop="address">
                      <avue-input-map :params="mapparams" placeholder="请选择地图" v-model="mapform" ></avue-input-map>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="经度" prop="longitude">
                        <el-input disabled="" v-model="form.longitude" placeholder="经度" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="纬度" prop="address">
                        <el-input disabled="" v-model="form.latitude" placeholder="纬度" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="详情" prop="content">
                    <el-input type="textarea" v-model="form.content" placeholder="请填写详情" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="附件" prop="common_inspection_files">
                    <el-upload multiple action="/api/admin/upload-file" list-type="picture-card" :file-list="commonInspectionFiles"
                      ref="pictureUploads" :auto-upload="true" :data="uploadOther"
                      :on-success="handlesuccess"
                      :on-error="handleError">
                      <i slot="default" class="el-icon-plus"></i>
                      <div slot="file" slot-scope="{file}">
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                        <span class="el-upload-list__item-actions">
                          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                            <i class="el-icon-zoom-in"></i>
                          </span>
                          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                            <i class="el-icon-delete"></i>
                          </span>
                        </span>
                      </div>
                    </el-upload>

                  </el-form-item>

                </el-col>
                <el-col :span="24">
                 <el-form-item label="反馈科室" prop="feedback_department_id">
                    <el-select class="width100" v-model="form.feedback_department_id" placeholder="请选择反馈科室">
                      <el-option v-for="item in selects.departments" :key="item.id" :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

              </el-row>

            </el-form>
          </el-scrollbar>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="resetEditForm('form')">取 消</el-button>
          <el-button type="primary" v-preventReClick @click="submitEditForm('form')">保存</el-button>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>






      <el-dialog :title="detailtitle" :visible.sync="dialogFormVisible" width="60%">
        <div class="dialogConcent" :style="{height:clientHeight+'px'}">
          <el-scrollbar style="flex: 1">
            <el-form :model="formdetail" :rules="rules" ref="formdetail" label-position="right" :label-width="formLabelWidth">
              <el-row>
                <el-col :span="10">
                  <el-form-item label="类型" prop="ask_type_id">
                    <div v-if="form.ask_type_detail">
                      {{form.ask_type_detail.value}}
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="10" :offset="4">
                 <el-form-item label="内容" prop="ask_content_id">
                   <div v-if="form.ask_content_detail">
                     {{form.ask_content_detail.value}}
                   </div>
                    <!-- {{form.ask_content_detail.value?form.ask_content_detail.value:""}} -->
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="地址" prop="address">
                      <avue-input-map :disabled="mapdisabled" :params="mapparams" placeholder="请选择地图" v-model="mapform" ></avue-input-map>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="经度" prop="longitude">
                        <el-input disabled="" v-model="form.longitude" placeholder="经度" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="纬度" prop="latitude">
                        <el-input disabled="" v-model="form.latitude" placeholder="纬度" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="详情" prop="content">
                    {{form.content}}
                  </el-form-item>
                </el-col>
               <el-col :span="24">
                  <el-form-item label="附件" class="common_inspection_files_check" prop="common_inspection_files_check">
                    <!-- <img v-if="commonInspectionFilesCheck.length>0" v-for="item in commonInspectionFilesCheck" :src="item.files.url" alt=""> -->


                  <el-upload multiple action="/api/admin/upload-file" list-type="picture-card" :file-list="commonInspectionFilesCheck"
                    ref="pictureUploads"
                    >
                    <div slot="file" slot-scope="{file}">
                      <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                      <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                          <i class="el-icon-zoom-in"></i>
                        </span>
                      </span>
                    </div>
                  </el-upload>

                  </el-form-item>
                </el-col>

                  <el-col :span="24" v-if="form.status!=3">
                      <el-form-item label="备注" prop="type_id">
                        <el-input type="textarea" v-model="formdetail.content" placeholder="请填写备注" autocomplete="off"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="form.status==1">
                     <el-form-item label="反馈科室" prop="feedback_department_id">
                        <el-select class="width100" v-model="formdetail.feedback_department_id" placeholder="请选择反馈科室">
                          <el-option v-for="item in selects.departments" :key="item.id" :label="item.name"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>

                    <el-col :span="24" v-if="form.status==2">
                      <el-form-item label="附件" prop="files_list">
                        <el-upload multiple class="upload-demo" :on-success="handlefilesuccess" :data="uploadOther"
                          action="/api/admin/upload-file" :on-remove="handlefileRemove" :before-remove="beforefileRemove"
                          :on-exceed="handlefileExceed" :file-list="filesList">
                          <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                      </el-form-item>
                    </el-col>

                    <el-col :span="24" v-if="form.status==3">
                        <el-form-item label="处理日志" prop="">

                        </el-form-item>
                        <el-table
                              :data="form.common_inspection_logs"
                              style="width: 90%;margin: 0 auto;">
                              <el-table-column
                                prop="created_at"
                                label="日期"
                                width="180">
                              </el-table-column>
                              <el-table-column
                                prop="content"
                                label="内容"
                                >
                              </el-table-column>
                              <el-table-column
                                prop="admin_id"
                                label="操作人"
                                width="180">
                              </el-table-column>
                            </el-table>

                    </el-col>
                  </el-row>





            </el-form>
          </el-scrollbar>
        </div>

        <div slot="footer" class="dialog-footer" v-if="form.status!=3">
          <el-button @click="resetForm('formdetail')">取 消</el-button>
          <el-button v-if="form.status==1" type="primary" v-preventReClick @click="submitForm('formdetail','2')">审核</el-button>
          <el-button v-if="form.status==2" type="primary" v-preventReClick @click="submitForm('formdetail','3')">办结</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
  import {
    listcommon,
    get,
    update,
    save,
    del
  } from '../../api/commonInspection/index.js'
  import {
    getToken
  } from '@/utils/auth'
  import {
    listdept
  } from "../../api/system/department.js"
  import {
    getparameteritem,
    getparameter
  } from "../../api/system/dictionary.js"
  import LxHeader from "@/components/LxHeader/index.vue";
  import AvueMap from 'avue-plugin-map'

  export default {
    components: {
      LxHeader,
      AvueMap
    },
    data() {
      return {

        tableHeight: 0,
        dialogFormVisible: false,
        showdialogFormVisible:false,
        formLabelWidth: "120px",
        clientHeight: 0,
        tableData: [],
        tableHeight: 900,
        searchFields: {
          KeyWord: ""
        },
        paginations: {
          page: 1,
          page_size: 15,
          total: 0
        },
        selects:{
          ask_types:[],
          ask_content:[],
          departments:[]
        },
        mapparams:{
            zoom: 11
        },
        mapform:[] ,
        mapdisabled:false,
        commonInspectionFiles:[],
        commonInspectionFilesCheck:[],
        dialogImageUrl:"",
        dialogVisible: false,
        disabled: false,
        filesList:[],
        detailtitle:"通用巡查",
        formdetail:{
          feedback_department_id:"",
          content:"",
          files_list:[],
          type:"",
        },
        form: {
          feedback_department_id:"",
          ask_type_id:"",
          ask_content_id:"",
          content:"",
          longitude:"",
          latitude:"",
          address:"",
          status:"",
          files_list:[]
        },

        rules: {
          ask_type_id: [{
          	required: true,
          	message: '请选择类型',
          	// 可以单个或者同时写两个触发验证方式
          	trigger: ['change', 'blur'],
          }],
          ask_content_id: [{
          	required: true,
          	message: '请选择内容',
          	// 可以单个或者同时写两个触发验证方式
          	trigger: ['change', 'blur'],
          }]
        },

        columns: [{
            field: "feedback_department_id",
            title: "反馈科室",
            type: "feedback_department_id",
             width:180
          },
          {
            field: "ask_type_name",
            title: "类型",
            type: "ask_type_id",
            align: "center",
             width:180
          },
          {
            field: "ask_content_name",
            title: "内容",
            type: "string",
            align: "center",
             width:180
          },
          {
            field: "address",
            title: "地址",
            type: "string",
            align: "lefft",
             width:360

          },
          {
            field: "status",
            title: "状态",
            type: "status",
            align: "center",
             width:120
          },
          {
            field: "user",
            title: "提交人",
            type: "format",
            align: "center",
             width:180
          },
          {
            field: "department",
            title: "提交科室",
            type: "format",
            align: "center",
             width:180
          },
          {
            field: "created_at",
            title: "提交日期",
            type: "string",
            align: "center",
            width:180
          },
          {
            field: "操作",
            title: "操作",
            width: 220,
            type: "opt",
            fixed:"right"
          }
        ],
        uploadOther: {
          token: ""
        },
        deptOptions: [],
        isStatus: [{
          id: 1,
          name: "已提交",
          opt: "上报"
        }, {
          id: 2,
          name: "已审核",
          opt: "编辑上报"
        }, {
          id: 3,
          name: "已办结",
          opt: "查看"
        }]
      }
    },
    created() {
      this.initLoad();
      this.load();

    },
    watch:{
      'mapform':function(val){
        this.form.longitude = val[0];
        this.form.latitude = val[1];
        this.form.address = val[2];
      }
    },
    methods: {
      initLoad() {
        var that = this;
        var clientHeight = document.documentElement.clientHeight
        var lxHeader_height = 96.5; //查询 头部
        var paginationHeight = 37; //分页的高度
        var topHeight = 50; //页面 头部
        let tableHeight = clientHeight - lxHeader_height - topHeight - paginationHeight - 20;
        that.tableHeight = tableHeight;

        this.uploadOther.token = getToken();

        getparameteritem("general_type").then(res => {
          this.selects.ask_types = res.detail
        })

        listdept().then(res => {
            this.selects.departments = res
        })


      },
      handleCurrentChange(page) {
        this.paginations.page = page;
        this.load();
      },
      load() {

        listcommon({
          page: this.paginations.page,
          page_size: this.paginations.page_size,
          keyword: this.searchFields.KeyWord
        }).then(response => {
          for(var m of response.data){
              // m.username = m.user?m.user.name:""
              m.ask_type_name = m.ask_type_detail?m.ask_type_detail.value:""
              m.ask_content_name = m.ask_content_detail?m.ask_content_detail.value:""
          }
          this.tableData = response.data;
          this.paginations.total = response.total;
        }).catch(error => {
          console.log(error)
          reject(error)
        });

      },
      show(obj) {
        this.clientHeight = document.documentElement.clientHeight - 84 - 110;
        this.dialogViewVisible = false;
        this.showdialogFormVisible = true;
        this.mapdisabled = false;
        this.formdetail.content = "";
        this.info(obj);
      },
      info(obj) {
        var that = this;
        get(obj.id).then(res => {
          let result = Object.assign(that.form, res);
          // this.$set(that.form,res);
          that.showAskContent(result.ask_type_id);
          if(result.status==2){
            this.detailtitle = '通用巡查办结'
          }
          if(result.status==1){
            this.detailtitle = '通用巡查审核'
          }
          // that.form = result;

          that.mapform = [result.longitude,result.latitude,result.address]

          let _files = [];
          for (var mod of result.common_inspection_files) {
            let m = Object.assign({}, mod);
            m.name = mod.original_name;
            m.url = mod.files.url
            _files.push(m);
          }
          that.commonInspectionFiles = _files;
          that.commonInspectionFilesCheck = _files;
          // that.formdetail = result;


          that.form = result
          that.formdetail.id = result.id;
          that.formdetail.feedback_department_id = result.feedback_department_id;
          console.log(that.formdetail);
          console.log(that.commonInspectionFiles);

        }).catch(error => {
          //reject(error)
        })
      },

      edit(obj, isnew) {
        this.form = this.$options.data().form;
        this.clientHeight = document.documentElement.clientHeight - 84 - 110;
        this.dialogFormVisible = true;
        this.showdialogFormVisible = false;
        this.mapdisabled = true;
        if(obj){
          this.info(obj);
        }


      },

      del(obj) {
        var that = this;
        if (obj) {
          this.$Modal.confirm({
            title: '确认要删除数据？',
            onOk: () => {
              del(obj.id).then(response => {
                this.$Message.success('操作成功');
                that.load();
              }).catch(error => {
                console.log(error)
                reject(error)
              })
            },
            onCancel: () => {
              //this.$Message.info('Clicked cancel');
            }
          });
        }
      },

      submitForm(formName, status) {
        var that = this;


        if (status == "2") {
          that.formdetail.type = status;
          // console.log(that.formdetail);
          // return;
          update(that.formdetail).then(response => {
            //console.log(response)
            this.$Message.success('操作成功');
            that.load();
            that.dialogFormVisible = false;
          }).catch(error => {
            //reject(error)
          })
        } else {
          that.formdetail.type = status;
          var _files = [];
          for(var m of this.filesList){
            if(m.response){
              this.formdetail.files_list.push({
                upload_id:m.response.id
              })
            }else{
              this.formdetail.files_list.push({
                upload_id:m.upload_id
              })
            }
          }
          console.log(that.formdetail)
          update(that.formdetail).then(response => {
            //console.log(response)
            this.$Message.success('操作成功');
            that.load();
            that.dialogFormVisible = false;
          }).catch(error => {
            //reject(error)
          })
        }
      },
      resetForm(formName) {
        var that = this;
        // that.fileList = [];
        this.$refs[formName].resetFields();
        this.filesList=[];
        this.commonInspectionFilesCheck = [];
        that.dialogFormVisible = false;
        that.dialogShowViewVisible = false;
      },
      submitEditForm(formName){
        var that = this;
        // files_list
        var _files = [];
        console.log(this.commonInspectionFiles);
        for(var m of this.commonInspectionFiles){
          if(m.response){
            this.form.files_list.push({
              upload_id:m.response.id
            })
          }else{
            this.form.files_list.push({
              upload_id:m.files.id
            })
          }
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            save(that.form).then(response => {
              //console.log(response)
              this.$Message.success('操作成功');
              that.load();
              that.dialogFormVisible = false;
              that.showdialogFormVisible = false;
            }).catch(error => {
              //reject(error)
            })
          } else {
            this.$Message.error('数据校验失败');
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetEditForm(formName) {
        var that = this;
        // that.fileList = [];
        this.$refs[formName].resetFields();
        that.mapform = [];
        this.commonInspectionFiles=[];
        that.dialogFormVisible = false;
        that.showdialogFormVisible = false;
      },
      showAskContent(val){
        getparameter({
          pid:val
        }).then(res =>{
          this.selects.ask_content = res.detail
        })
      },
      showAskContentChange(val){
        getparameter({
          pid:val
        }).then(res =>{
          this.selects.ask_content = res.detail
          this.form.ask_content_id = ""
        })
      },
      handleRemove(file) {
        console.log(file);
        for (var i = 0; i < this.commonInspectionFiles.length; i++) {
          if (this.commonInspectionFiles[i].url == file.url) {
            this.commonInspectionFiles.splice(i, 1)
          }
        }
      },
      handlePictureCardPreview(file) {

        this.dialogImageUrl = file.url;
        console.log(file);
        this.dialogVisible = true;
      },
      handlesuccess(response, file, fileList) {
        console.log(fileList);
        this.commonInspectionFiles = fileList;
        this.$message({
          message: '上传成功',
          type: 'success'
        });
      },

      handleError(err,file,fileList){
        this.$message.error('上传失败，重新上传');
      },

      handlefileRemove(file, fileList) {
        let listUrl = [];
         console.log(fileList)
        for (var m of fileList) {
          if (m.response)
            listUrl.push({
              "upload_id":m.response.id,
              'name':m.name
            });
          else
            listUrl.push({
              "upload_id":m.response.id,
              'name':m.name
            });
        }
        this.filesList = listUrl;
      },
      handlefileExceed(files, fileList) {},
      beforefileRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handlefilesuccess(response, file, fileList) {
        let listUrl = [];
        console.log(fileList)
        for (var m of fileList) {
          if (m.response)
            listUrl.push({
              "upload_id":m.response.id,
              'name':m.name
            });
          else
            listUrl.push({
              "upload_id":m.response.id,
              'name':m.name
            });

        }
        this.filesList = listUrl;
      },




    }
  }
</script>

<style>
  .dialogConcent {
    overflow-y: auto;
  }
  .width100{
    width:100%;
  }
  .common_inspection_files_check .el-upload.el-upload--picture-card{
    display: none;
  }
</style>
