<template>
  <div class="patrol-work-order">
    <div class="inner-form">
      <el-form
        v-form
        data-vv-scope="taskManageForm"
        :model="form"
        :rules="rules"
        ref="taskManageForm"
        label-width="80px"
      >
        <el-form-item
          label="巡检类型"
          prop="type"
        >
          <dict-select
            :disabled="currentNode == 2"
            v-model="form.type"
            dictCode="xjlx"
            type="radio"
          ></dict-select>
        </el-form-item>
        <el-form-item
          label="巡检路段"
          prop="roadSegmentName"
        >
          <el-input
            :disabled="currentNode == 2"
            v-model="form.roadSegmentName"
            placeholder="请选择巡检路段"
            style="width: 100%"
            ref="roadSegmentName"
            @focus="openRoad"
          >
            <el-button
              type="primary"
              @click="openRoad"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
          <!-- <company-info-selector
                        v-model="form.roadSegmentName"
                        :valueName="form.companyIds"
                        @handleChanged="handleChanged"
                        @value="companyValue"
                    /> -->
        </el-form-item>
        <el-form-item
          label="巡检人"
          prop="rummagerName"
        >
          <eip-user-selector
            :permission="currentNode == 2 ? 'r' : 'b'"
            v-model="form.rummagerName"
            append-to-body
            :single="true"
            :config="{
                            id: 'form.rummagerId',
                            account: 'form.rummagerAccounts',
                        }"
            placeholder="请选择巡检人"
          />
        </el-form-item>
        <el-form-item
          label="巡检日期"
          prop="patrolDate"
        >
          <el-date-picker
            :disabled="currentNode == 2"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
            v-model="form.patrolDate"
            type="date"
            placeholder="选择巡检日期"
            align="right"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="巡检内容"
          prop="content"
        >
          <el-input
            v-model="form.content"
            type="textarea"
            :disabled="currentNode == 2"
          ></el-input>
        </el-form-item>
        <!-- 添加病害 -->
        <el-card
          class='card-box'
          v-if='currentNode == 2'
        >
          <el-button
            type="primary"
            @click="addListItem"
            style="margin-bottom: 20px"
            icon="el-icon-plus"
          >
            添加病害</el-button>

          <el-table
            :data="tableData"
            border
            stripe
            style="max-width: 100%; min-width: 100%"
            max-height="360"
          >
            <el-table-column
              prop="companyId"
              label="公司名称"
              min-width="130"
              fixed="left"
              align='center'
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.companyId"
                  placeholder="请选择路段"
                >
                  <el-option
                    v-for="item in companyOptions"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  ></el-option>
                </el-select>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="roadId"
              label="路段名称"
              min-width="130"
              fixed="left"
              align='center'
            ><template slot-scope="scope">
                <el-select
                  v-model="scope.row.roadId"
                  placeholder="请选择路段"
                >
                  <el-option
                    v-for="item in roadData"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="type"
              label="检查类别"
              min-width="130"
              align='center'
            >
              <template slot-scope="scope">
                <dict-select
                  dictCode="xjlb"
                  :hasDefaultOption="true"
                  v-model="scope.row.type"
                  style="width: 100%"
                  @select="(val, obj) => handleSelectValue(val, obj,'xjlb')"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="description"
              label="病害描述"
              min-width="130"
              align='center'
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.price"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="direction"
              label="方向"
              min-width="130"
              align='center'
            >
              <template slot-scope="scope">
                <dict-select
                  dictCode="fx"
                  :hasDefaultOption="true"
                  v-model="scope.row.direction"
                  style="width: 100%"
                  @select="(val, obj) => handleSelectValue(val, obj,'fx')"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="startPeg"
              label="起点桩号"
              min-width="140"
              align='center'
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.money"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="endPeg"
              label="止点桩号"
              min-width="130"
              align='center'
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.auditPrice"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="categoryId"
              label="病害类别"
              min-width="130"
              align='center'
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.categoryId"
                  placeholder="请选择"
                  @change="(val) => changesele(val, scope.row.key)"
                  clearable
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="detailsId"
              label="病害细目"
              min-width="140"
              align='center'
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.detailsId"
                  placeholder="请选择"
                  clearable
                  @change='(val) => subSubChange(val,scope.row)'
                >
                  <el-option
                    v-for="item in scope.row.subOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="position"
              label="病害部位"
              min-width="130"
              align='center'
            >
              <template slot-scope="scope">
                <dict-select
                  dictCode="bhbw"
                  :hasDefaultOption="true"
                  v-model="scope.row.position"
                  style="width: 100%"
                  @select="(val, obj) => handleSelectValue(val, obj,'bhbw')"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="handlingSituation"
              label="处理情况"
              min-width="130"
              align='center'
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.handlingSituation"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in handlingSituationOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="temporary"
              label="是否暂存"
              min-width="90"
              align='center'
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.temporary"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in temporaryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="receiverMoney"
              label="病害参数(单位:毫米)"
              align='center'
            >
              <el-table-column
                prop="paramLength"
                label="长"
                align='center'
                min-width='140'
              >
                <template slot-scope="scope">
                  <el-input-number
                    :min="0"
                    :precision="2"
                    :controls="false"
                    v-model="scope.row.paramLength"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                prop="paramWidth"
                label="宽"
                align='center'
                min-width='140'
              >
                <template slot-scope="scope">
                  <el-input-number
                    :min="0"
                    :precision="2"
                    :controls="false"
                    v-model="scope.row.paramWidth"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                prop="paramHeight"
                label="高"
                align='center'
                min-width='140'
              >
                <template slot-scope="scope">
                  <el-input-number
                    :min="0"
                    :precision="2"
                    :controls="false"
                    v-model="scope.row.paramHeight"
                  ></el-input-number>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column
              prop="deadline"
              label="超时日期"
              min-width="140"
              align='center'
            >
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.deadline"
                  type="date"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              width="80"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  size="small"
                  icon="el-icon-delete"
                  @click="deleteListItem(scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <road-info-dialog
        ref="road"
        :single="true"
        :fullscreen="true"
        @select="handleSelectRoad"
      ></road-info-dialog>
    </div>
  </div>
</template>

<script>
import {helper} from '../../../public/hotent.helper.js'
import req from '@/request.js'
import utils from '@/utils'
import basicData from '@/api/basicData.js'
import RoadInfoDialog from '@/components/dialog/RoadInfoDialog.vue'
import companyInfoSelector from '@/components/selector/companyInfoSelector.vue'
import EipUserSelector from '@/components/eipControl/selector/EipUserSelector.vue'
import DictSelect from '@/components/dict/DictSelect.vue'
export default {
  name: 'PatrolWorkOrder', // 巡检工单
  components: {
    RoadInfoDialog,
    EipUserSelector,
    DictSelect,
    companyInfoSelector,
  },
  data() {
    return {
      currentNode: 1,
      form: {
        roadSegmentName: '',
        rummagerId: '',
        rummagerName: '',
        patrolDate: '',
        type: '1',
        content: '',
        props1: '',
      },
      tableData: [],
      options: [],
      cbkm: [],
      roadData: [],
      temporaryOptions: [
        {label: '否', value: 0},
        {label: '是', value: 1},
      ], //是否暂存
      handlingSituationOptions: [
        {label: '未处理', value: 0},
        {label: '处理中', value: 1},
        {label: '已处理', value: 2},
        {label: '观察记录', value: 3},
      ],
      companyOptions: [], //公司信息
      rules: {
        type: [
          {
            required: true,
            message: '请选择巡检类型',
            trigger: 'blur',
          },
        ],
        roadSegmentName: [
          {
            required: true,
            message: '请选择巡检路段',
            trigger: 'blur',
          },
        ],
        rummagerName: [
          {required: true, message: '请选择巡检人', trigger: 'blur'},
        ],
        patrolDate: [
          {
            required: true,
            message: '请选择巡检日期',
            trigger: 'blur',
          },
        ],
        content: [
          {
            required: true,
            message: '请填写巡检内容',
            trigger: 'blur',
          },
        ],
      },
      typeOptions: [],
    }
  },
  created() {
    this.typeOptions = utils.getDictItemsFromCache('xjlx')
    this.getDataInfo()
  },
  mounted() {
    this.currentNode = this.$route.query.node
    const _this = this
    window.saveData = this.saveData
    this.id = utils.getUrlKey('id')
    let isEdit = utils.getUrlKey('isEdit')
    this.disabled = isEdit == 'r' ? true : false
    if (this.id) {
      req
        .get(window.context.yhxt + '/siteInspection/v1/get/' + this.id)
        .then((res) => {
          if (res.data) {
            res.data.type ? (res.data.type = res.data.type + '') : null
            _this.form = res.data
          }
        })
    }
  },
  methods: {
    /* 添加病害 */
    //按钮添加一行数据
    addListItem() {
      let length = this.tableData.length
      // let workOrderInformationId =
      //   this.form.workOrderInformation && this.form.workOrderInformation.id
      //     ? this.form.workOrderInformation.id
      //     : ''
      // let contractId =
      //   this.form.workOrderInformation &&
      //   this.form.workOrderInformation.contractId
      //     ? this.form.workOrderInformation.contractId
      //     : ''
      let newData = {
        // todo 回显时需加上工单id合同id，key
        key: length + 1,
        companyId: this.companyOptions[0].id ? this.companyOptions[0].id : '', //公司信息
        companyName: this.companyOptions[0].name
          ? this.companyOptions[0].name
          : '', //公司信息
        roadId: this.roadData[0].id ? this.roadData[0].id : '', //路段信息
        type: 1,
        direction: 1,
        categoryId: '', //病号类别id
        subjectName: '', //病号类别名称
        subOption: [], //病害细目,
        detailsId: '', //病害细目id
        dsubjectName: '', //病害细目名称
        temporary: 1, //是否暂存
        position: 1, //病害部位
        handlingSituation: 1, //处理情况
      }
      this.tableData.push(newData)
    },
    deleteListItem(index) {
      this.tableData.splice(index, 1)
    },
    //根据病害类别获取病害细目
    changesele(value, key) {
      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.tableData.forEach((item) => {
            if (item.key == key) {
              item.subOption = arr
              item.detailsId = item.subOption[0].value
              item.dsubjectName = item.subOption[0].label
            }
          })
          //赋值类别名称
          this.options.forEach((item) => {
            if (item.value == value) {
              this.form.detailList.forEach((item1) => {
                if (item1.key == key) {
                  item1.subjectName = item.label
                  item1.categoryId = item.value
                }
              })
            }
          })
        } else {
          this.tableData.forEach((item) => {
            if (item.key == key) {
              item.subOption = []
              item.subSubjectName = ''
            }
          })
        }
      })
    },
    //细目改变事件,赋值细课目名称
    subSubChange(val, obj) {
      // console.log(val, obj)
      if (obj.subOption) {
        obj.subOption.forEach((item) => {
          if (item.value == val) {
            this.form.detailList.forEach((item1) => {
              if (item1.key == obj.key) {
                item1.detailsId = item.value
                item1.dsubjectName = item.label
              }
            })
          }
        })
      }
    },
    //获取路段下拉信息
    getDataInfo() {
      // 获取路段信息
      basicData.getRoadManagement().then((res) => {
        this.roadData = res.rows
      })
      // 获取病害类别
      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,
            })
          })
        })
      }
      //获取公司信息
      this.$http.post("${yhxt}/Company/v1/getCompany").then(res => {
        res.data.forEach(item => {
          this.companyOptions.push({
            id: item.id,
            name: item.name
          })
        })
      })
    },
    //深层拷贝回去公司名称
    deepClone(obj) {
      let objClone = Array.isArray(obj) ? [] : {}
      if (obj && typeof obj === 'object') {
        for (let key in obj) {
          if (obj.hasOwnProperty(key)) {
            //判断ojb子元素是否为对象，如果是，递归复制
            if (obj[key] && typeof obj[key] === 'object') {
              objClone[key] = this.deepClone(obj[key])
            } else {
              if (obj[key] == obj.name) {
                this.companyOptions.push({
                  id: obj.id,
                  name: obj.name,
                })
              }
              //如果不是，简单复制
              objClone[key] = obj[key]
            }
          }
        }
      }
    },
    //字典回调,赋值
    handleSelectValue(val, obj, str) {
      if (str == 'xjlb') {
        this.tableData.forEach((item) => {
          if (item.key == obj.key) {
            item.typeName = obj.name
          }
        })
      } else if (str == 'fx') {
        this.tableData.forEach((item) => {
          if (item.key == obj.key) {
            item.directionName = obj.name
          }
        })
      } else if (str == 'bhbw') {
        this.tableData.forEach((item) => {
          if (item.key == obj.key) {
            item.positionName = obj.name
          }
        })
      }
    },
    /* 添加病害结束 */
    saveData() {
      const _this = this
      //验证表单是否填写完
      this.$refs.taskManageForm.validate((pass) => {
        if (pass) {
          //请求保存提交
          console.log(this.form, 'this.form')
          this.$http
            .post(
              '${yhxt}/siteInspection/v1/saveSiteInspectionSpecial',
              this.form
            )
            .then((res) => {
              if (res.data.state) {
                let params = {
                  type: 'saveData',
                  state: true,
                  businessKey: res.data.value.id,
                  sysCode: '',
                }
                // params.vars = {
                //     props1: this.forms.props1,
                // }
                hotent.sendMessage(params)
              }
            })
        }
      })
    },
    handleSelectRoad(data) {
      this.form.roadSegmentName = data.name
      this.form.roadSegmentId = data.id
      this.form.routeId = data.routeId
      this.form.routeName = data.routeName
      this.$refs.roadSegmentName.focus()
      this.$refs.roadSegmentName.blur()
      top.postMessage(
        {
          handlerType: 'isMaskShow',
          params: {
            isMaskShow: false,
          },
        },
        '*'
      )
    },
    //所属路线打开弹框
    openRoad() {
      this.$refs.road.open()
    },
  },
}
</script>

<style lang='scss' scoped>
.index-inner {
  display: flex;
  justify-content: center;
  height: 100%;
  background-color: #fff;
}
.patrol-work-order {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  background: #fff;
  .inner-form {
    width: 600px;
    margin: 0 auto;
    .card-box {
      max-width: 100%;
      min-width: 1200px;
      box-sizing: border-box;
      position: absolute;
      top: 280px;
      left: 50%;
      transform: translateX(-50%);
    }
  }
}

//  ::v-deep  .el-select-dropdown__item.hover,
// .el-select-dropdown__item:hover {
//   background-color: #409eff !important;
//   color: #fff !important;
// }
</style>
