<template>
  <div>
    <el-dialog
      v-if="firdialogVisible"
      title="病害信息"
      :visible.sync="firdialogVisible"
      width="1000px"
      :open="open"
      destroy-on-close
      append-to-body
    >
      <el-container style="height: 100%">
        <el-main style="padding: 10px; height: 100%">
          <ht-table
            @load="loadData"
            :data="data"
            :pageResult="pageResult"
            :selection="true"
            quick-search-props="rummager"
            :show-export="false"
            :show-custom-column="false"
            ref="htTable"
            @row-dblclick="handleEdit"
          >
            <template v-slot:toolbar>
              <el-button
                size="small"
                @click="showDialog()"
                icon="el-icon-plus"
                type="primary"
                >添加</el-button
              >
              <el-button size="small" icon="el-icon-plus" type="primary"
                >导出列表</el-button
              >
              <ht-delete-button
                url="${form}/disease/v1/"
                :htTable="$refs.htTable"
                @after-delete="afterDelete"
                >删除</ht-delete-button
              >
            </template>
            <template>
              <ht-table-column
                prop="roadName"
                label="路段名称"
                :sortable="true"
                :show-overflow-tooltip="true"
              >
              </ht-table-column>
              <ht-table-column
                prop="type"
                label="检查类别"
                :show-overflow-tooltip="true"
                :filters="getDictData('xjlb')"
              >
                <template v-slot="{row}">
                  <div>{{ getDictName('xjlb', row.type) }}</div>
                </template>
              </ht-table-column>
              <ht-table-column
                prop="description"
                label="病害描述"
                :sortable="true"
                :show-overflow-tooltip="true"
              >
              </ht-table-column>
              <ht-table-column
                prop="direction"
                label="方向"
                :filters="getDictData('qlfx')"
                :show-overflow-tooltip="true"
              >
                <template v-slot="{row}">
                  <el-tag>{{ getDictName('qlfx', row.direction) }}</el-tag>
                </template>
              </ht-table-column>
              <ht-table-column
                prop="subjectName"
                label="病害类别"
                :sortable="true"
                :show-overflow-tooltip="true"
              >
              </ht-table-column>
              <ht-table-column
                prop="dsubjectName"
                label="病害细目"
                :sortable="true"
                :show-overflow-tooltip="true"
              >
              </ht-table-column>
              <ht-table-column
                prop="position"
                label="病害部位"
                :sortable="true"
                :show-overflow-tooltip="true"
              >
              </ht-table-column>
              <ht-table-column
                prop="handlingSituation"
                label="处理情况"
                :sortable="true"
                :show-overflow-tooltip="true"
              >
              </ht-table-column>
            </template>
          </ht-table>
        </el-main>
      </el-container>
    </el-dialog>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="1000px"
      :before-close="handleCancel"
      destroy-on-close
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        v-if="dialogVisible"
      >
        <el-row>
          <el-col :span="12"
            ><el-form-item label="巡检类别" prop="type">
              <!-- <el-input
                v-model="form.type"
                :disabled="true"
              ></el-input>  -->
              <dict-select
                dictCode="xjlb"
                :hasDefaultOption="true"
                v-model="form.type"
                style="width: 100%"
                disabled
              /> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="方向" prop="direction">
              <!-- <el-input v-model="form.direction"></el-input>  -->
              <dict-select
                dictCode="qlfx"
                :hasDefaultOption="true"
                clearable
                v-model="form.direction"
                style="width: 100%"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="起点桩号" prop="startPeg">
              <el-input v-model="form.startPeg"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12"
            ><el-form-item label="结束桩号" prop="endPeg">
              <el-input v-model="form.endPeg"></el-input> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><el-form-item label="病害类别" prop="categoryId">
              <!-- <el-input v-model="form.categoryId"></el-input> -->
              <el-select
                v-model="form.categoryId"
                placeholder="请选择"
                @change="val => changesele(val)"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="病害细目" prop="detailsId">
              <!-- <el-input v-model="form.detailsId"></el-input>  -->
              <el-select
                v-model="form.detailsId"
                placeholder="请选择"
                @change="dsubchange"
              >
                <el-option
                  v-for="item in cbkm"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><el-form-item label="病害部位" prop="position">
              <el-input v-model="form.position"></el-input> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="路段" prop="roadName">
              <el-input v-model="form.roadName" disabled></el-input>
              <!-- <el-input
                v-model="form.roadName"
                ref="routeName"
                @focus="handleFocusRouter"
              >
                <el-button
                  type="primary"
                  @click="openRoute"
                  slot="append"
                  icon="el-icon-search"
                ></el-button>
              </el-input> -->
              <!-- <sction-info-selector
                v-model="form.roadName"
                :value="form.roadName"
                @changed="changed"
                @value="value"
                disabled
              /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否暂存" prop="temporary">
              <!-- <el-input v-model="form.temporary"></el-input> -->
              <el-select v-model="form.temporary" placeholder="请选择">
                <el-option
                  v-for="item in optionsss"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="病害高(mm)" prop="paramHeight">
              <el-input type="number" v-model="form.paramHeight"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="病害长(mm)" prop="paramLength">
              <el-input type="number" v-model="form.paramLength"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="病害宽(mm)" prop="paramWidth">
              <el-input type="number" v-model="form.paramWidth"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="病害描述" prop="description">
              <el-input v-model="form.description" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件管理">
              <file-upload
                :dadToSon="dadToSon"
                @sonToDad="sonToDad"
              ></file-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <!-- <el-button @click="enclosure">附件管理</el-button> -->
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="附件管理"
      :visible.sync="dialogVisibleEnclosure"
      v-if="dialogVisibleEnclosure"
      width="1000px"
      :before-close="handleCloseEnclosure"
      v-loading="downLoading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <el-upload
        class="upload-button"
        ref="fileUp"
        :multiple="false"
        :headers="headers"
        :show-file-list="false"
        :action="downLoad"
        :accept="accept"
        :file-list="files"
        :on-change="handleChange"
        :on-success="success"
        :on-error="error"
        :on-progress="progress"
        style="display: inline-block"
      >
        <el-tooltip placement="top" effect="dark">
          <div slot="content">
            附件格式支持:附件大小限制：单个文件不超过50MB
          </div>
          <el-button
            size="small"
            :icon="loading === false ? 'el-icon-upload' : 'el-icon-loading'"
            :disabled="disabled"
          >
            上传文件
          </el-button>
        </el-tooltip>
      </el-upload>
      <el-button style="margin-left: 10px" @click="downLoadImg"
        >导出文件</el-button
      >
      <el-button
        style="margin-left: 10px"
        type="danger"
        @click="handleEnclosureDel"
        >删除</el-button
      >
      <el-table
        :data="enclosureData"
        border
        ref="multipleTable"
        style="width: 100%; margin-top: 10px"
        @selection-change="handleSelectionChangeEnclosure"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="name" label="附件名" align="center" width="180">
        </el-table-column>
        <el-table-column
          prop="type"
          align="center"
          label="附件类型"
          width="180"
        >
        </el-table-column>
        <el-table-column prop="suffix" label="后缀" align="center" width="180">
        </el-table-column>
        <el-table-column prop="url" align="center" label="附件路径">
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import req from '@/request.js'
import basicData from '@/api/basicData.js'
import BridgeDialog from '@/components/dialog/BridgeDialog.vue'
import sctionInfoSelector from '@/components/selector/sctionInfoSelector.vue'
import fileUpload from '@/components/upload/fileUpload.vue'
export default {
  components: {
    BridgeDialog,
    sctionInfoSelector,
    fileUpload
  },
  computed: mapState({
    // submitUrl: function () {
    //   return `${window.context.portal}/portal/commonBasic/v1/`
    // },
    downLoad: function() {
      return `${window.context.portal}/bridgeRegularCheck/v1/minioRegularCheckUpload?sourceId=${this.sourceId}`
    },
    deleteUrl: function() {
      return window.context.yhxt + '/disease/v1/removesDisease'
    },
    headers: state => {
      return {Authorization: `Bearer ${state.login.currentUser.token}`}
    }
  }),
  data() {
    return {
      dadToSon: {
        bizPath: 'disease',
        fileList: []
      },
      accessories: [],
      options: [],
      //附件数据
      enclosureData: [],
      //附件管理所需id
      sourceId: '',
      //删除附件管理ids
      ids: [],
      cbkm: [],
      loading: false, //上传附件加载控制
      disabled: false, //按钮禁用控制
      downLoading: false, //文件导出加载控制
      accept:
        '.jpg,.jpeg,.png,.bmp,.pdf,.JPG,.JPEG,.PBG,.BMP,.PDF,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.rtf,.txt,.zip,.rar,.vsd,.dwg,',
      dialogVisibleEnclosure: false,
      files: [],
      dialogVisible: false,
      firdialogVisible: false,
      data: [],
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      optionsss: [
        {value: '0', label: '否'},
        {value: '1', label: '是'}
      ],
      row: [],
      title: '',
      form: {
        direction: 1,
        temporary: '0',
        roadName: ''
      },
      rules: {
        type: [{required: true, message: '巡检类别', trigger: 'blur'}],
        direction: [{required: true, message: '方向', trigger: 'blur'}],
        startPeg: [{required: true, message: '起点桩号', trigger: 'blur'}],
        endPeg: [{required: true, message: '结束桩号', trigger: 'blur'}],
        categoryId: [{required: true, message: '病害类别', trigger: 'blur'}],
        detailsId: [{required: true, message: '病害细目', trigger: 'blur'}],
        position: [{required: true, message: '病害部位', trigger: 'blur'}],
        paramHeight: [{required: true, message: '病害高(mm)', trigger: 'blur'}],
        paramLength: [{required: true, message: '病害长(mm)', trigger: 'blur'}],
        paramWidth: [{required: true, message: '病害宽(mm)', trigger: 'blur'}],
        description: [{required: true, message: '病害描述', trigger: 'blur'}]
      },
      relevanceId: ''
    }
  },
  methods: {
    sonToDad(data) {
      console.log(data)
      this.form.accessories = data
    },
    handleSelectionChangeEnclosure(rows) {
      rows.forEach(item => {
        this.ids.push(item.id)
      })
    },
    //去重
    unique(arr) {
      for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i] == arr[j]) {
            //第一个等同于第二个，splice方法删除第二个
            arr.splice(j, 1)
            j--
          }
        }
      }
      return arr
    },
    //附件管理删除
    handleEnclosureDel() {
      this.downLoading = true
      const ids = this.unique(this.ids)
      // console.log(ids.join(','))
      const strs = ids.join(',')
      console.log(strs, '231')
      this.$http
        .remove('${form}/bridgeRegularCheck/v1/removesRegularCheck?ids=' + strs)
        .then(res => {
          console.log(res, 'sc')
          if (res.data.state) {
            this.$message.success('附件删除成功')
            this.downLoading = false
          } else {
            this.$message.error('附件删除失败')
            this.downLoading = false
          }
          this.getEnclosureData(this.sourceId)
          //清空ids
          this.ids = []
        })
    },
    //附件导出
    downLoadImg() {
      this.downLoading = true
      const ids = this.unique(this.ids)
      const strs = ids.join(',')
      req
        .download(
          window.context.portal +
            '/bridgeRegularCheck/v1/downloadRegularCheckUpload?ids=' +
            strs
        )
        .then(res => {
          this.downLoading = false
          this.$refs.multipleTable.clearSelection()
          this.ids = []
        })
      // basicData.downLoadEnclosureManagement(strs).then(res => {
      //   //清空ids
      //   this.ids = []
      // })
    },
    progress(event, file, fileList) {
      //将图标改成加载图标
      this.loading = true
      //将按钮禁用
      this.disabled = true
    },
    error(response, file, fileList) {
      this.$message.error('文件上传失败')
      delete this.uploadingFiles[Base64.encode(file.name)]
    },
    success(response, file, fileList) {
      this.$message.success('文件上传成功')
      //重新加载数据
      this.getEnclosureData(this.sourceId)
      //将图标改成上传图标
      this.loading = false
      //将按钮解禁
      this.disabled = false
    },
    handleChange(file, fileList) {
      console.log(file, fileList, 'dddd')
    },
    handleCloseEnclosure(done) {
      this.enclosureData = []
      done()
    },
    changesele(value) {
      this.options.forEach(item => {
        if (value == item.value) {
          this.form.subjectName = item.label
          this.form.categoryId = item.value
        }
      })
      let arr = []
      basicData.getCostAccountManagement(value).then(res => {
        if (res.data.length > 0) {
          res.data.forEach(item => {
            if (item.pcode == value) {
              arr.push({
                label: item.subjectName,
                value: item.subjectCode
              })
            }
            this.cbkm = arr
            this.form.detailsId = arr[0].value
            this.form.dsubjectName = arr[0].label
          })
        }
      })
    },
    dsubchange(val) {
      this.cbkm.forEach(item => {
        if (item.value == val) {
          this.form.dsubjectName = item.label
          this.form.detailsId = item.value
        }
      })
      this.$forceUpdate()
    },
    getEnclosureData(id) {
      const params = {
        pageBean: {
          page: 1,
          pageSize: 20,
          showTotal: true
        },
        params: {},
        querys: [
          {
            group: 'main',
            operation: 'EQUAL',
            parentGroup: '',
            property: 'sourceId',
            relation: 'AND',
            value: id
          }
        ],
        sorter: []
      }
      basicData.getEnclosurevirus(params).then(res => {
        this.enclosureData = res.rows
      })
    },
    enclosure() {
      this.$refs.ruleForm.validate(bool => {
        if (bool) {
          if (this.title === '【修改病害】') {
            this.dialogVisibleEnclosure = true
            this.getEnclosureData(this.sourceId)
          } else {
            this.$message.error('请先保存该表单才能进入附件管理')
          }
        } else {
          this.$message.error('请先保存该表单才能进入附件管理')
        }
      })
    },
    handleSubmit() {
      this.form.relevanceId = this.relevanceId
      this.$refs.ruleForm.validate(bool => {
        if (bool) {
          //请求保存提交
          basicData.addDiseaseSave(this.form).then(res => {
            console.log(res)
            this.$message.success('保存成功')
            this.options = []
            this.cbkm = []
            this.dadToSon = {
              fileList: []
            }
            this.dialogVisible = false
            this.$refs.htTable.load()
          })
        }
      })
    },
    openRoute() {
      this.$refs.route.open()
    },
    handleFocusRouter() {
      this.$refs.route.open()
    },
    handleCancel() {
      this.dialogVisible = false
      this.dadToSon = {
        fileList: []
      }
    },
    open(row) {
      console.log(row)
      this.form.type = row.type
      this.form.typeName = row.typeName
      this.form.roadName = row.roadSegmentName
      this.form.roadId = row.roadSegmentId
      this.row = row
      this.firdialogVisible = true
      this.relevanceId = row.id
    },
    handleEdit(data) {
      if (this.options.length == 0) {
        let data = 'CBKM'
        basicData.getCostAccountManagement(data).then(res => {
          res.data.forEach(item => {
            this.options.push({
              label: item.subjectName,
              value: item.subjectCode
            })
          })
        })
      }
      console.log(data, 'binghai')
      this.$http.get('${form}/disease/v1/get/' + data.id).then(res => {
        this.dialogVisible = true
        this.dadToSon.fileList = res.data.accessories
        this.files = res.data.accessories //修改时加上原来的图片上传
        this.form = res.data
      })
      this.title = '【修改病害】'
      // this.form = data
      // this.dialogVisible = true
      this.sourceId = data.id
    },
    loadData(param, cb) {
      param.querys = [
        {
          property: 'RELEVANCE_ID_',
          value: this.row.id
        }
      ]
      this.$http
        .post('${form}/disease/v1/getJson', param)
        .then(
          resp => {
            this.data = resp.data.rows
            this.pageResult = {
              page: resp.data.page,
              pageSize: resp.data.pageSize,
              total: resp.data.total
            }
          },
          error => {
            reject(error)
          }
        )
        .finally(() => {
          if (cb) {
            cb()
          }
        })
    },
    showDialog() {
      this.form = {
        type: this.form.type,
        direction: 1,
        temporary: '0',
        roadName: this.form.roadName,
        roadId: this.form.roadId
      }
      console.log(this.form, 'ddddddd')
      this.dialogVisible = true
      this.title = '【添加病害】'
      if (this.options.length == 0) {
        let data = 'CBKM'
        basicData.getCostAccountManagement(data).then(res => {
          res.data.forEach(item => {
            this.options.push({
              label: item.subjectName,
              value: item.subjectCode
            })
          })
        })
      }
    },
    //路段信息赋值
    changed(obj) {
      this.form.roadName = obj.name
      this.form.roadName = obj.id
    },
    //默认赋值为第一条数据的值
    value(obj) {
      console.log(obj)
      if (this.title == '【添加病害】') {
        this.form.roadName = obj.name
        this.form.roadName = obj.id
      }
    },
    afterDelete() {}
  }
}
</script>

<style lang="scss" scoped>
/deep/.el-dialog::-webkit-scrollbar {
  display: none;
}
/deep/ .el-dialog__header {
  border-bottom: 1px solid #ebeef5;
}
</style>
