<!-- 土壤检测发布 -->
<template>
  <div class="table_box">
    <!-- header -->
    <div class="formStyle">
      <el-form :inline="true">
        <el-form-item prop="name1">
          <span>服务名称：</span>
          <el-input v-model="name1.name"
                    style="width: 260px"
                    placeholder="请输入关键字查询"></el-input>
        </el-form-item>
        <el-button type="primary"
                   @click="handlequery"> 查询</el-button>
        <el-button type="primary"
                   @click="handleAdd">添加</el-button>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="right-main">
      <div style="box-shadow: 0px 0px 10px 2px rgb(153 153 153 / 20%);margin-top: 20px;padding: 16px 16px 0 16px;background: #fff;">
        <!-- 表格 -->
        <Table v-loading="loading"
               :header="headerName"
               :columnWidths="columnWidths"
               :data="tableData"
               :slotColumns="slotColumns">
          <el-table-column label="序号"
                           width="80px"
                           type="index"></el-table-column>
          <template width="160px"
                    slot="name"
                    slot-scope="scope">
            <div>{{ scope.row.agrotechnicalName}}</div>
          </template>
          <template width="160px"
                    slot="classification"
                    slot-scope="scope">
            <div>{{ scope.row.classification}}</div>
          </template>
          <template width="160px"
                    slot="price"
                    slot-scope="scope">
            <div>￥{{scope.row.price}}/{{scope.row.chargeUnit}}</div>
          </template>
          <template width="160px"
                    slot="state"
                    slot-scope="scope">
            <div>{{scope.row.state == 0? '未上架' : '已上架'}}</div>
          </template>
          <template slot="oprate">
            <el-table-column label="操作"
                             width="260"
                             align="center">
              <template slot-scope="scope">
                <el-button @click="handleEdit(scope.row)"
                           type="text"
                           size="small"
                           class="edit-btn">
                  <i class="line-icon line-edit-icon"></i>查看
                </el-button>
                <el-button @click="handleEdit1(scope.row)"
                           type="text"
                           size="small"
                           class="edit-btn">
                  <i class="line-icon line-edit-icon"></i>编辑
                </el-button>
                <el-button @click="deldata(scope.row.agrotechnicalId)"
                           type="text"
                           size="small"
                           class="edit-btn">
                  <i class="line-icon line-edit-icon"></i>删除
                </el-button>
                <el-button @click="handleEdit2(scope.row)"
                           type="text"
                           size="small"
                           class="edit-btn">
                  <i class="line-icon line-edit-icon"></i><span>{{scope.row.state == 0 ? '上架':'下架'}}</span>
                </el-button>
              </template>
            </el-table-column>
          </template>
        </Table>
      </div>
      <!-- 弹出层 -->
      <!-- 添加与编辑共用弹出层 -->
      <el-dialog :title="titleMasger"
                 :visible.sync="dialogVisible"
                 :before-close="handleClose"
                 width="500px">
        <!-- 查看 -->
        <div v-if="lookcontent"
             class="lookcontent">
          <div><span>名称：</span><span>{{params1.agrotechnicalName}}</span></div>
          <div><span>类型：</span><span>{{params1.classification}}</span></div>
          <div><span>单价：</span><span>￥{{params1.price}} /{{params1.chargeUnit}}</span></div>
          <div><span>服务机构：</span><span>{{params1.facilitatingAgency}}</span></div>
          <div><span>联系人：</span><span>{{params1.contacts}}</span></div>
          <div><span>联系电话：</span><span>{{params1.phone}}</span></div>
          <div><span>服务详情：</span><span>{{params1.description}}</span></div>
          <div><span>图片：</span><span v-if="!this.imagesUrl1[0]">该类型服务暂无相关介绍图片。</span></div>
          <el-carousel :interval="1000"
                       arrow="always"
                       v-if="this.imagesUrl1[0]">
            <el-carousel-item v-for="item in imagesUrl1"
                              :key="item">
              <img :src="item" />
            </el-carousel-item>
          </el-carousel>
        </div>
        <el-form ref="elForm"
                 :rules="rules"
                 :model="params1"
                 label-width="80px"
                 v-else>
          <el-form-item label="名称"
                        prop="agrotechnicalName">
            <el-input type="text"
                      v-model="params1.agrotechnicalName"
                      clearable
                      :style="{width: '100%'}"></el-input>
          </el-form-item>
          <el-form-item label="类型"
                        prop="agrotechnicalTypeId">
            <el-select v-model="params1.agrotechnicalTypeId"
                       placeholder="请选择类型"
                       :style="{width: '100%'}">
              <el-option v-for="(item) in type"
                         :key="item.id"
                         @change="typechange(item.id)"
                         :label="item.agrotechnicalType"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单价"
                        prop="price">
            <el-input type="text"
                      v-model="params1.price"></el-input>
          </el-form-item>
          <el-form-item label="服务机构"
                        prop="facilitatingAgency">
            <el-input type="text"
                      v-model="params1.facilitatingAgency"></el-input>
          </el-form-item>
          <el-form-item label="计价单位"
                        prop="chargeUnit">
            <el-input type="text"
                      v-model="params1.chargeUnit"></el-input>
          </el-form-item>
          <el-form-item label="联系人"
                        prop="contacts">
            <el-input type="text"
                      v-model="params1.contacts"></el-input>
          </el-form-item>
          <el-form-item label="联系电话"
                        prop="phone">
            <el-input type="text"
                      v-model="params1.phone"></el-input>
          </el-form-item>
          <el-form-item label="服务详情"
                        prop="description">
            <el-input type="textarea"
                      :rows="3"
                      placeholder="请输入内容"
                      v-model="params1.description"></el-input>
          </el-form-item>
          <el-form-item label="图片"
                        prop="imagesUrl">
            <el-upload list-type="picture-card"
                       action=""
                       :on-remove="handleRemove"
                       :http-request="handleRequest"
                       :file-list="fileList">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible1">
              <img width="100%"
                   :src="dialogImageUrl">
            </el-dialog>
          </el-form-item>
        </el-form>
        <div slot="footer"
             class="dialog-footer"
             v-if="disabled">
          <el-button plain
                     @click.native="cancel">取消</el-button>
          <!-- 添加提交 -->
          <el-button type="primary"
                     @click.native.prevent="onSubmit"
                     v-if="choose">确定</el-button>
          <!-- 编辑提交 -->
          <el-button type="primary"
                     @click.native.prevent="onSubmit1"
                     v-else>确定</el-button>
        </div>
      </el-dialog>
      <!--分页-->
      <div style="text-align: center"
           class="pagination">
        <page-nation :total="totals"
                     @pageChange="pageChange"
                     :defaultPage.sync="currentPage"
                     :pageSizes="pageSizes"></page-nation>
      </div>
    </div>
  </div>
</template>

<script>
//接口请求方法导入
import {
  soiltableList,// 初始化列表数据
  deltettableList, // 删除
  postdatalist,  // 添加
  getbyidtableList, // id查询
  getquery,// 模糊查询
  putdatalist,// 编辑
  getAgrotechnicalTypeAll
} from '../../apis/modules/soildetection'
import {
  ossPrepare,
} from "../../apis/modules/auth.js";
import axios from "axios";
//公共组件导入
import pageNation from "../common/PageNation.vue";
import Table from '../common/Table.vue';
export default {
  name: 'SoilDetection2',
  components: {
    pageNation,
    Table,
  },
  data () {
    var valiNumberPass = (rule, value, callback) => {
      //包含小数的数字
      let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
      if (value === "") {
        callback(new Error("请输入内容"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入数字"));
      } else {
        callback();
      }
    };
    return {
      tableData: [], // 初始化数据
      // 传递参数
      params1: {
        agrotechnicalName: '',
        agrotechnicalTypeId: '',
        price: '',
        facilitatingAgency: '',
        chargeUnit: '',
        contacts: '',
        phone: '',
        description: '',
        imagesUrl: '',
        state: 0
      },
      id: { agrotechnicalId: '' },
      tabPosition: "审核列表",
      loading: false,// loading加载
      // 分页相关
      pageSizes: [10, 30, 50, 120], //控制每页显示的条数
      currentPage: 1,
      totals: 0,
      pageSize: 10,
      // params参数
      params: {
        pageSize: 10,
        page: 1
      },
      fileList: [],
      dialogVisible1: false,
      dialogImageUrl: '',
      name1: { name: '', pageSize: 10, page: 1 },// 模糊查询参数
      choose: false,// 查询 || 编辑 提价逻辑判断开关
      titleMasger: '',// 弹出层标题
      dialogVisible: false,// 弹出层开关
      disabled: false,//弹出层编辑/查看/添加切换判定开关
      lookcontent: false,
      imagesUrl1: [],
      type: [],
      // 表单验证
      rules: {
        agrotechnicalName: [{ required: true, message: "请输入服务名称", trigger: "blur" }],
        agrotechnicalTypeId: [{ required: true, message: "请输入服务类型", trigger: "blur" }],
        classification: [{ required: true, message: "请输入服务类型", trigger: "blur" }],
        price: [{ required: true, validator: valiNumberPass, message: "服务价格不能为空且必须是纯数字", }],
        facilitatingAgency: [{ required: true, message: "请输入服务机构", trigger: "blur" }],
        chargeUnit: [{ required: true, message: "请输入计价单位", trigger: "blur" }],
        contacts: [{ required: true, message: "请输入联系人", trigger: "blur" }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { pattern: /^1(3|4|5|7|8|9)\d{9}$/, message: '手机号格式错误', trigger: 'blur' }],
        description: [{ required: true, message: "请输入服务详情", trigger: "blur" }],
      },
      headerName: { name: "名称", classification: "类型", price: "单价", state: "状态", },// table表格头部名称
      slotColumns: ['name', 'classification', 'price', 'state'],//插槽调用
      columnWidths: {}, //控制某一列的宽度，设置对应字段即可
    }
  },
  created () { this.initdata() },
  methods: {
    // 获取初始化数据
    initdata () {
      this.loading = true //刷新加载loading
      soiltableList(this.params)
        .then(res => {
          this.tableData = res.d.items
          this.totals = res.d.total
          this.loading = false
        })
    },
    // 查询按钮
    handlequery () {
      // 查询输入框空数据验证，可选择默认请求当前页数据，也可选择提示用户信息
      if (!this.name1.name) {
        //this.$message.warning('查询内容为空，请输入查询条件！') //提示信息
        this.initdata() //请求当前页数据
      } else {
        getquery(this.name1)
          .then(res => {
            this.tableData = res.d.items
          })
      }
    },
    // 分页查询
    pageChange (pageNum) {
      this.params.page = pageNum.page
      this.params.pageSize = pageNum.pageSize
      if (this.name1.name)
        this.initdata()
    },
    // id查询封装方法 --> 多处调用
    byiddata (row) {
      this.id.agrotechnicalId = row
      getbyidtableList(this.id)
        .then(res => {
          this.params1 = res.d
          console.log(this.params1);
          this.imagesUrl1 = res.d.imagesUrl.split(';')
          if (this.imagesUrl1[0]) {
            this.imagesUrl1.forEach(item => {
              if (item != "") {
                let obj = {}
                obj['url'] = item
                this.fileList.push(obj)
              }
            })
          }
          this.imagesUrl1 = this.imagesUrl1.filter(item => {
            return item != ""
          })
          console.log(this.imagesUrl1);
        })
    },
    // 查看
    handleEdit (row) {
      this.titleMasger = "查看";
      this.dialogVisible = true;
      this.disabled = false
      this.lookcontent = true
      this.byiddata(row.agrotechnicalId)
    },
    // 添加按钮
    handleAdd () {
      this.params1 = {}
      this.imagesUrl1 = []
      this.titleMasger = "添加";
      this.lookcontent = false
      this.dialogVisible = true;
      this.disabled = true
      this.choose = true
      this.gettype()
    },
    // 添加提交
    onSubmit () {
      this.params1.imagesUrl = this.imagesUrl1.join(';')
      console.log(this.params1.imagesUrl);
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          postdatalist(this.params1)
            .then(res => {
              this.initdata()
              this.dialogVisible = false;
            })
        }
      })
    },
    // 获取类型
    hanldtype (id) {
      this.params1.agrotechnicalTypeId = id
    },
    // 编辑按钮
    handleEdit1 (row) {
      this.titleMasger = "编辑";
      this.dialogVisible = true;
      this.lookcontent = false
      this.disabled = true
      this.choose = false
      this.byiddata(row.agrotechnicalId)
      this.gettype()
    },
    // 编辑提交
    onSubmit1 () {
      const par = this.params1
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          par.imagesUrl = {}
          par.imagesUrl = this.imagesUrl1.join(";")
          console.log(par.imagesUrl);
          putdatalist(par)
            .then(res => {
              this.dialogVisible = false;
              this.initdata()
            })
        }
      })
    },
    // 删除数据
    deldata (id) {
      this.id.agrotechnicalId = id
      deltettableList(this.id)
        .then(res => {
          if (res.status == 0) {
            this.$message.success('删除成功')
            this.initdata()
          } else {
            this.$message.error('删除失败')
          }
        })
    },
    // 上架
    handleEdit2 (row) {
      this.id.agrotechnicalId = row.agrotechnicalId
      getbyidtableList(this.id)
        .then(res => {
          this.params1 = res.d
          if (row.state == 0) {
            this.params1.state = 1
          } else {
            this.params1.state = 0
          }
          putdatalist(this.params1)
            .then(res => {
              if (res.status == 0 && row.state == 0) {
                this.$message.success('上架成功')
                this.initdata()
              } else {
                this.$message.success('下架成功')
                this.initdata()
              }
            })
        })
    },
    // 取消
    cancel () {
      this.fileList = []
      this.dialogVisible = false;
      this.$refs['elForm'].resetFields() //重置表单验证
    },
    // 弹出层关闭之前
    handleClose (done) {
      if (!this.titleMasger == "查看") {
        this.$refs['elForm'].resetFields() //重置表单验证
      }
      this.fileList = []
      done();

    },
    // 获取类型方法
    gettype () {
      getAgrotechnicalTypeAll()
        .then(res => {
          console.log(res);
          this.type = res.d
        })
    },
    typechange (id) {
      this.params1.agrotechnicalTypeId = id
    },
    // 上传图片
    handleRequest (res) {
      this._getPicByOss(res.file, pic => {
        this.uploadData = pic;
        let file = res.file;
        let fileName = file.name;
        if (!!fileName) {
          ossPrepare({ objectName: fileName }).then(res => {
            let params = new FormData();
            let formData = res.data.formData;
            params.append("OSSAccessKeyId", formData.OSSAccessKeyId);
            params.append("key", formData.key);
            params.append("policy", formData.policy);
            params.append("signature", formData.signature);
            params.append(
              "success_action_status",
              formData.success_action_status
            );
            params.append("file", file);
            axios({
              url: res.data.host,
              method: "post",
              data: params,
              header: {
                "access-Control-Allow-Origin": "*",
                "Content-Type": "application/x-www-form-urlencoded"
              }
            }).then(res => {
              this.guaranteeSlip(res.config.url + "/" + formData.key);
            });
          });
        }
      });
    },
    guaranteeSlip (urled) {
      this.imagesUrl1.push(urled)
      console.log(this.imagesUrl1);
    },
    handleRemove (file) {
      // console.log("你删除了图片");
      // 1.获取将要删除图片的临时路径
      const filePath = file.url;
      console.log(filePath);
      // 2.从pictureList数组中，找到图片对应的索引值
      const i = this.fileList.filter((item) => {
        return item.url != filePath
      });
      console.log(i);
      this.imagesUrl1 = []
      i.forEach(item => {
        this.imagesUrl1.push(item.url + ";")
      })
      console.log(this.imagesUrl1);
    },
  },
}
</script>

<style  scoped>
.formStyle {
  box-shadow: 0px 0px 10px 2px rgba(153, 153, 153, 0.2);
  margin-top: 20px;
  padding: 16px;
  background: #fff;
  height: 40px;
  line-height: 40px;
  padding-left: 20px;
}
.lookcontent {
  line-height: 26px;
}
img {
  width: 100%;
  height: 100%;
}
</style>
