<template>
  <div>
    <div class="borderless">
      <div class="customer-head">
        <div class="customer-back">
          <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
            @click="backToList">返回列表
          </el-button>
        </div>
        <div class="add-customer-btn">
          <!--<el-button type="info" icon="el-icon-printer" size="small" @click.stop="openReport()">报表打印-->
          <!--</el-button>-->
            <el-button v-if="form.dispatchingWorkers == 2" type="warning" size="small" :disabled="option.dispatchWorkers" @click="editCustomer(2)">
                撤销派工
            </el-button>
            <el-button v-else type="warning" size="small" :disabled="option.disabled && (form.dispatchingWorkers == 0 || form.dispatchingWorkers == 1)" @click="editCustomer(1)">
                派工
            </el-button>

          <el-button type="primary" size="small"
            class="el-button--small-yh" :disabled="!option.disabled" @click.stop="openEdit">编辑
          </el-button>
          <el-button type="primary" size="small" :disabled="option.disabled" @click="editCustomer(0)">
            保存数据
          </el-button>
        </div>
      </div>
      <trade-card title="基础资料" style="margin-top: 60px" v-loading="loadingBtn">
        <avue-form ref="form" class="trading-form" v-model="form" :option="option">
          <!--<template slot="corpName">-->
          <!--  &lt;!&ndash;<crop-select v-model="form.corpId" corpType="KH" :disabled="option.disabled"&ndash;&gt;-->
          <!--  &lt;!&ndash;  @getCorpData="getCorpData"></crop-select>&ndash;&gt;-->
          <!--    -->
          <!--</template>-->

          <template slot="deviceName">
            <el-select v-model="form.deviceName" clearable
                       @change='deviceNameChange' :disabled="option.disabled" filterable placeholder="请选择设备">
              <el-option
                v-for="item in deviceList"
                :key="item.cname"
                :label="item.cname"
                :value="item.cname">
              </el-option>
            </el-select>
          </template>

          <template slot="maintenanceWorkerId">
            <el-select v-model="form.maintenanceWorkerId" clearable
                       @change='maintenanceWorkerIdChange' :disabled="option.disabled" filterable placeholder="请选择维修工">
              <el-option
                v-for="item in maintenanceWorkersList"
                :key="item.id"
                :label="item.realName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>

            <template slot="maintenanceAmount">
                <el-input v-model="form.maintenanceAmount" type="number" disabled
                          placeholder="请输入" size="small" :controls="false" style="width:100%;"></el-input>
            </template>
        </avue-form>
      </trade-card>
      <trade-card title="维修项目" v-loading="loadingBtn">
        <avue-crud ref="crud" :option="optionList" :data="data" :table-loading="loading" @saveColumn="saveColumn"
          @resetColumn="resetColumn" :cell-style="cellStyle">
          <template slot="headerSerial">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click.stop="addRow"
              :disabled="option.disabled" circle></el-button>
          </template>

            <template slot="costName" slot-scope="{ row, index }">
                <el-input v-if="row.$cellEdit" v-model="row.costName"
                          placeholder="请输入" size="small" :controls="false" style="width:100%;"></el-input>
                <span v-else>{{ row.costName }}</span>
            </template>
            <template slot="amount" slot-scope="{ row, index }">
                <el-input v-if="row.$cellEdit" v-model="row.amount"
                                 placeholder="请输入" size="small" :controls="false" style="width:100%;"
                @blur="amountblur">
                </el-input>
                <span v-else>{{ row.amount }}</span>
            </template>
            <template slot="remarks" slot-scope="{ row, index }">
                <el-input v-if="row.$cellEdit" v-model="row.remarks"
                          placeholder="请输入" size="small" :controls="false" style="width:100%;"></el-input>
                <span v-else>{{ row.remarks }}</span>
            </template>

          <template slot="menu" slot-scope="{ row, index }">
            <el-button size="small" type="text" :disabled="option.disabled" @click="rowCell(row, index)">{{
                row.$cellEdit ? "保存" : "修改"
            }}</el-button>
            <el-button size="small" type="text" :disabled="option.disabled" @click="rowDel(row, index)">删除
            </el-button>
          </template>
        </avue-crud>
      </trade-card>

      <containerTitle title="上传附件"></containerTitle>
      <c-upload v-loading="loadingBtn" typeUpload="CD"
        deleteUrl="/api/blade-sales-part/maintenanceFiles/remove" :data="maintenanceFiles" display
        :enumerationValue="35.1"></c-upload>




      <dictbiz-dialog ref="dictbiz" title="添加单位" code="unit" parentId="1585962784498225154" @closed="getAllWorkDicts">
      </dictbiz-dialog>



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

<script>
import { optionList } from "./js/optionList";
import reportDialog from "@/components/report-dialog/main";
import { multiply, sum, subtract } from "@/util/calculate";
import {getList as yhgetList, userList} from "@/api/system/user";

import {
    maintenanceDetail,
    maintenanceDispatchingWorkers,
    maintenanceFeesRemove, maintenanceRevokeDispatchingWorkers,
    maintenanceSubmit
} from "@/api/basicData/maintenanceQ";
import {
    bladeUserList,
    corpequipmentarchivesitemList,
    corpequipmentarchivesList,
} from "@/api/basicData/EquipmentArchives";
import {date} from "mockjs/src/mock/random/date";
export default {
  name: "index",
  data() {
    return {

      // 设备list
      deviceList: [],
      // 维修工list
      maintenanceWorkersList: [],

      loadingBtn: false,
      addressTitle: null,
      form: {},
      form2: {
      },
      form3: {

      },
      data: [],

      option: {
        menuBtn: false,
        labelWidth: 90,
        disabled: false,
        dispatchWorkers: false,
        column: [
          {
            label: "客户名称",
            prop: "archivesId",
            type: "select",
              filterable:true,
              dicData:[],
            props: {
                label: 'corpName',
                value: 'id'
            },
            // rules: [
            //   {
            //     required: true,
            //     message: "",
            //     trigger: "blur"
            //   }
            // ],
              change: (val) => {
                if(val.value == '') return
                  for(let item of val.column.dicData) {
                      if (val.value == item.id){
                          this.form.corpName = item.corpName
                          this.form.corpId = item.corpId
                          this.form.corpTel = item.contactsTel
                          this.form.deviceAddress = item.address
                          this.form.corpDescribe = item.corpName
                          // 设备名称
                          corpequipmentarchivesitemList({pid:item.id}).then(res=>{
                              this.findObject(this.option.column, "deviceName").dicData = res.data.data.records
                              this.deviceList = res.data.data.records
                          })
                          break;
                      }
                  }
              },
            span: 8,
          },
            {
                label: "客户电话",
                prop: "corpTel",
                span: 8,
                rules: [
                    {
                        required: true,
                        message: "",
                        trigger: "blur"
                    }
                ],
            },
            {
                label: "单号",
                prop: "sysNo",
                disabled:true,
                span: 8,
            },
            {
                label: "地址",
                prop: "deviceAddress",
                span: 24,
                rules: [
                    {
                        required: true,
                        message: "",
                        trigger: "blur"
                    }
                ],
            },
            {
                label: "设备名称",
                prop: "deviceName",
                dicData:[],
                dataType: "string",
                type: "select",
                props: {
                    label: 'cname',
                    value: 'cname'
                },
                span: 8,
                change: (val) => {
                    val.column.dicData.map(item=>{
                        if (val.value == item.cname){
                            this.form.deviceId = item.id
                            this.form.deviceDescribe = item.cname

                            this.form.categoryitem = item.categoryitem
                            this.form.categoryitemId = item.categoryitemId
                            this.form.factoryId = item.factoryId
                            this.form.factoryName = item.factoryName
                        }
                    })
                },
            },
            {
                label: "报修日期",
                prop: "repairReportDate",
                type: "date",
                format: "yyyy-MM-dd",
                valueFormat: "yyyy-MM-dd 00:00:00",
                span: 8,
            },
            {
                label: "完成日期",
                prop: "completeDate",
                disabled: true,
                type: "date",
                format: "yyyy-MM-dd",
                valueFormat: "yyyy-MM-dd 00:00:00",
                span: 8,
            },
            {
                label: "故障描述",
                prop: "faultDescribe",
                type: "textarea",
                minRows: 3,
                span: 24,
            },
            {
                label: "维修工名称",
                prop: "maintenanceWorkerId",
                dicData:[],
                dataType: "string",
                type: "select",
                props: {
                    label: 'realName',
                    value: 'id'
                },
                span: 8,
                change: (val) => {
                    if(val.value == '') return
                    for(let item of val.column.dicData) {
                        if (val.value == item.id){
                            this.form.maintenanceWorkerName = item.name
                            this.form.maintenanceWorkerTel = item.phone
                        }
                    }
                },
            },
            {
                label: "维修工电话",
                prop: "maintenanceWorkerTel",
                span: 8,
            },
            {
                label: "维修金额",
                prop: "maintenanceAmount",
                disabled:true,
                span: 8,
                type: "number",
            },
            {
                label: "客户描述",
                prop: "corpDescribe",
                type: "textarea",
                minRows: 3,
                span: 8,
                change:(val)=>{
                    if (!this.form.corpId){
                        this.form.corpName = val.value
                    }
                }
            },
            {
                label: "设备描述",
                prop: "deviceDescribe",
                type: "textarea",
                minRows: 3,
                span: 8,
                change:(val)=>{
                    if (!this.form.deviceId) {
                        this.form.deviceName = val.value
                    }
                }
            },
          {
            label: "备注",
            prop: "remarks",
            type: "textarea",
            minRows: 3,
            span: 8,
          }
        ]
      },
        // 商品信息列表配置
      optionList: {},
        // 商品产品下拉数据
      goodsoptions: [],
        // 附件
        maintenanceFiles: [],
        loading:false,
    };
  },
  props: {
    detailData: {
      type: Object
    }
  },
  components: {
    reportDialog
  },

  async created() {
    this.optionList = optionList
      // 获取字典数据
      this.getAllWorkDicts()
      // 查看是否要id调用详情
    if (this.detailData.id) {
        this.option.disabled = true
      this.getDetail(this.detailData.id);
    } else {
      // 报修日期默认当天
      var time = new Date();
      var day = ("0" + time.getDate()).slice(-2);
      var month = ("0" + (time.getMonth() + 1)).slice(-2);
      var today = time.getFullYear() + "-" + month + "-" + day;
      this.form.repairReportDate = today;
    }
    if (this.detailData.status == 1) {
      this.option.disabled = true;
      this.option.dispatchWorkers = true;
    }

  },
  methods: {
      // 获取下拉字典
    getAllWorkDicts() {
        // 获取地址信息
        // this.findObject(this.option.column, "deviceAddress").dicData = JSON.parse(localStorage.getItem('areaTypeTree'))
        // 获取客户名称（档案列表）
        corpequipmentarchivesList().then(res=>{
            this.findObject(this.option.column, "archivesId").dicData = res.data.data.records
        })
        bladeUserList({roleAlias:'维修工'}).then(res=>{
          console.log(res.data.data)
            this.findObject(this.option.column, "maintenanceWorkerId").dicData = res.data.data
            this.maintenanceWorkersList = res.data.data
          console.log(this.maintenanceWorkersList)

        })
    },
    cellStyle() {
      return "padding:0;height:40px;";
    },
    deviceNameChange(cname) {
      for (const item of this.deviceList) {
        if (item.cname == cname) {

          this.form.deviceId = item.srcId
          this.form.deviceDescribe = item.cname

          this.form.categoryitem = item.categoryitem
          this.form.categoryitemId = item.categoryitemId
          this.form.factoryId = item.factoryId
          this.form.factoryName = item.factoryName
        }
      }
    },
    maintenanceWorkerIdChange(id) {
      for (const item of this.maintenanceWorkersList) {
        if (item.id == id) {
          this.form.maintenanceWorkerName = item.name
          this.form.maintenanceWorkerTel = item.phone
        }
      }
    },
      // 维修项目的失焦事件
      amountblur(){
        let sum = 0
        this.data.map(item=>{
            sum += Number(item.amount)
        })
        this.form.maintenanceAmount = sum
      },

    amountChange() {
      let val = 0
      this.data.forEach(e => {
        val = sum(val, e.amount)
        this.form.purchaseAmount = val
        this.form.orderAmount = subtract(this.form.purchaseAmount, this.form.thisUsedProfit)
      })
    },
    // countChange(row) {
    //   row.amount = multiply(row.price, row.storageInQuantity)
    //   row.storageAmount = multiply(row.purchaseAmount, row.storageInQuantity)
    //   let val = 0
    //   this.data.forEach(e => {
    //     val = sum(val, e.amount)
    //     this.form.purchaseAmount = val
    //     this.form.orderAmount = subtract(this.form.purchaseAmount, this.form.thisUsedProfit)
    //   })
    // },
      // 获取详情数据
    getDetail(id) {
      this.loadingBtn = true
        maintenanceDetail({ id: id })
        .then(res => {
          this.form = res.data.data;
          this.data = res.data.data.maintenanceFees;
          this.maintenanceFiles = res.data.data.maintenanceFiles ? res.data.data.maintenanceFiles : [];
        })
        .finally(() => {
          this.loadingBtn = false;
        });
    },
      // 客户下拉框
    getCorpData(row) {
      if (row) {
        this.form.corpName = row.cname
        this.form.corpTel = row.tel
      } else {
        this.form.corpName = null
        this.form.corpTel = null
      }
    },

    addRow() {
        // this.data.push({ $cellEdit: true, storageId: this.form.storageId })
       this.$refs["form"].validate((valid, done) => {
          done();
          if (valid) {
             this.data.push({ $cellEdit: true, storageId: this.form.storageId })
          } else {
             return false;
          }
       });
    },
    rowCell(row, index) {
        if (!row.costName) {
            return this.$message.warning('维修项目不能为空');
        }
        if (!row.amount) {
            return this.$message.warning('金额不能我空');
        }
      if (row.$cellEdit == true) {
        this.$set(row, "$cellEdit", false);
      } else {
        this.$set(row, "$cellEdit", true);
      }
    },
      // 费用删除
    rowDel(row, index) {
      this.$confirm("确定删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id) {
          maintenanceFeesRemove({ids:row.id}).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.data.splice(index, 1);
          });
        } else {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.data.splice(index, 1);
        }
        this.amountblur()
      });
    },
    //修改提交触发0 派工1 撤销派工2
    editCustomer(index) {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          if (!this.form.corpName) {
              return this.$message.error('请维护客户描述');
          }
            if (!this.form.deviceDescribe) {
                return this.$message.error('请维护设备描述');
            }

            if(index == 1) {
                if (!this.form.maintenanceWorkerId) {
                    return this.$message.error('请选择维修工');
                }
                if (!this.form.maintenanceWorkerTel) {
                    return this.$message.error('请填写维修工电话');
                }
            }

            let arr = this.data.map(item=>{
                return {
                    id:item.id?item.id:null,
                    costId:item.costId?item.costId:null,
                    costName:item.costName,
                    amount:item.amount,
                    number:1,
                    price:item.amount,
                    currency:'CNY',
                    settlementAmount:item.settlementAmount?item.settlementAmount:0,
                    remarks:item.remarks
                }
            })
            let list = this.maintenanceFiles.map(item=>{
                item.sort = 1
                return item
            })
            const obj = {
                id:this.form.id?this.form.id:null,
                sysNo:this.form.sysNo?this.form.sysNo:null,
                deviceId:this.form.deviceId,
                deviceName:this.form.deviceName,
                corpId:this.form.corpId,
                corpName:this.form.corpName,
                corpTel:this.form.corpTel,
                archivesId: this.form.archivesId,
                deviceAddress:this.form.deviceAddress,
                faultDescribe:this.form.faultDescribe,
                maintenanceWorkerId:this.form.maintenanceWorkerId,
                maintenanceWorkerName:this.form.maintenanceWorkerName,
                maintenanceWorkerTel:this.form.maintenanceWorkerTel,
                maintenanceAmount:this.form.maintenanceAmount,
                repairReportDate:this.form.repairReportDate,
                settlementAmount:this.form.settlementAmount?this.form.settlementAmount:0,
                remarks:this.form.remarks,
                status:this.form.status,
                categoryitem:this.form.categoryitem, // 功能分类
                factoryId:this.form.factoryId, // 工厂
                factoryName:this.form.factoryName, // 工厂
                deviceDescribe:this.form.deviceDescribe,
                corpDescribe:this.form.corpDescribe,

                categoryitemId:this.form.categoryitemId,

                maintenanceFees:arr,
                maintenanceFiles:list
            }
            this.loadingBtn = true;

            this.maintenanceSubmitfun(obj,index)
        } else {
          return false;
        }
      });
    },
      // 派工接口
      maintenanceDispatchingWorkersfun(obj){
          maintenanceDispatchingWorkers(obj).then(res=>{
              this.$message.success("派工成功");
              this.form = res.data.data;
              this.data = res.data.data.maintenanceFees;
              this.maintenanceFiles = res.data.data.maintenanceFiles ? res.data.data.maintenanceFiles : [];
              this.option.disabled = true;
              this.option.dispatchWorkers = true;
          })
      },
      // 撤销派工
      maintenanceRevokeDispatchingWorkersfun(obj){
          maintenanceRevokeDispatchingWorkers(obj).then(res=>{
              this.$message.success("撤销派工成功");
              this.form = res.data.data;
              this.data = res.data.data.maintenanceFees;
              this.maintenanceFiles = res.data.data.maintenanceFiles ? res.data.data.maintenanceFiles : [];
              this.option.disabled = true;
              this.option.dispatchWorkers = true;
          })
      },
      // 保存接口
      maintenanceSubmitfun(obj,index){
          maintenanceSubmit(obj).then(res => {
              this.form = res.data.data;
              // this.data = res.data.data.maintenanceFees;
              // this.maintenanceFiles = res.data.data.maintenanceFiles ? res.data.data.maintenanceFiles : [];
              this.detailData.status = 1
              this.option.disabled = true;
              this.option.dispatchWorkers = true;

              if (index == 0) {
                  this.$message.success("保存成功");
                  this.getDetail(this.form.id)
              }else if (index == 1) {
                  this.maintenanceDispatchingWorkersfun(obj)
              }else if (index == 2) {
                  this.maintenanceRevokeDispatchingWorkersfun(obj)
              }else {}
              this.$refs.crud.refreshTable();
          }).finally(() => {
              this.loadingBtn = false;
          });
      },

    async saveColumn() {
      const inSave = optionList
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    async resetColumn() {
      this.optionList = optionList;
      const inSave = optionList
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.getAllWorkDicts()
        this.$message.success("重置成功");
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    openEdit() {
      // this.detailData.status = 2
      if (this.form.dispatchingWorkers == 2) {
        this.option.dispatchWorkers = false
      } else {
        this.option.disabled = false
      }
      // this.option = this.$options.data().option;
      // this.$refs.crud.refreshTable();
    },
    //返回列表
    backToList() {
      this.$emit("goBack");
    },

  },
  watch: {
    // data: function (rows) {
    //   let val = 0
    //   rows.forEach(e => {
    //     val = sum(val, e.amount)
    //     this.form.purchaseAmount = val
    //     this.form.orderAmount = subtract(this.form.purchaseAmount, this.form.thisUsedProfit)
    //   })
    // }
  }
};
</script>

<style lang="scss" scoped>
.trading-form ::v-deep .el-form-item {
  margin-bottom: 8px !important;
}

::v-deep .el-dialog__body {
  padding: 0px 20px 15px 20px;
}

::v-deep .el-form-item__error {
  display: none !important;
}

.img-form ::v-deep .el-form-item {
  height: 150px;
  line-height: 150px;
  margin-bottom: 8px !important;
}

.img-form ::v-deep .avue-upload__icon {
  font-size: 20px;
  width: 150px;
  height: 150px;
  line-height: 150px;
}

::v-deep .el-table .cell {
  padding: 0 2px !important;
}

::v-deep .avue-crud .el-table .el-form-item__label {
  left: -1px;
}

.addressTabs {
  display: flex;
  justify-content: center;

  span {
    width: 100px;
    font-size: 18px;
    font-weight: 600;
    text-align: center;
  }
}
</style>
